diff --git a/MP42.xcodeproj/project.pbxproj b/MP42.xcodeproj/project.pbxproj index 1a24da4..15da830 100644 --- a/MP42.xcodeproj/project.pbxproj +++ b/MP42.xcodeproj/project.pbxproj @@ -9,12 +9,112 @@ /* Begin PBXBuildFile section */ A9B9C1F1182391DF00416A4E /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C1F0182391DF00416A4E /* Cocoa.framework */; }; A9B9C1FB182391DF00416A4E /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = A9B9C1F9182391DF00416A4E /* InfoPlist.strings */; }; - A9B9C1FF182391DF00416A4E /* MP42.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C1FE182391DF00416A4E /* MP42.m */; }; A9B9C206182391DF00416A4E /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C205182391DF00416A4E /* XCTest.framework */; }; A9B9C207182391DF00416A4E /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C1F0182391DF00416A4E /* Cocoa.framework */; }; A9B9C20A182391DF00416A4E /* MP42.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C1ED182391DF00416A4E /* MP42.framework */; }; A9B9C210182391DF00416A4E /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = A9B9C20E182391DF00416A4E /* InfoPlist.strings */; }; A9B9C212182391DF00416A4E /* MP42Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C211182391DF00416A4E /* MP42Tests.m */; }; + A9B9C2661823923200416A4E /* MP42AACImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C21B1823923100416A4E /* MP42AACImporter.h */; }; + A9B9C2671823923200416A4E /* MP42AACImporter.mm in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C21C1823923100416A4E /* MP42AACImporter.mm */; }; + A9B9C2681823923200416A4E /* MP42AC3Importer.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C21D1823923100416A4E /* MP42AC3Importer.h */; }; + A9B9C2691823923200416A4E /* MP42AC3Importer.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C21E1823923100416A4E /* MP42AC3Importer.m */; }; + A9B9C26A1823923200416A4E /* MP42AudioConverter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C21F1823923100416A4E /* MP42AudioConverter.h */; }; + A9B9C26B1823923200416A4E /* MP42AudioConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2201823923100416A4E /* MP42AudioConverter.m */; }; + A9B9C26C1823923200416A4E /* MP42AudioTrack.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2211823923100416A4E /* MP42AudioTrack.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C26D1823923200416A4E /* MP42AudioTrack.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2221823923100416A4E /* MP42AudioTrack.m */; }; + A9B9C26E1823923200416A4E /* MP42AVFImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2231823923100416A4E /* MP42AVFImporter.h */; }; + A9B9C26F1823923200416A4E /* MP42AVFImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2241823923100416A4E /* MP42AVFImporter.m */; }; + A9B9C2701823923200416A4E /* MP42BitmapSubConverter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2251823923100416A4E /* MP42BitmapSubConverter.h */; }; + A9B9C2711823923200416A4E /* MP42BitmapSubConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2261823923100416A4E /* MP42BitmapSubConverter.m */; }; + A9B9C2721823923200416A4E /* MP42CCImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2271823923100416A4E /* MP42CCImporter.h */; }; + A9B9C2731823923200416A4E /* MP42CCImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2281823923100416A4E /* MP42CCImporter.m */; }; + A9B9C2741823923200416A4E /* MP42ChapterTrack.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2291823923100416A4E /* MP42ChapterTrack.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C2751823923200416A4E /* MP42ChapterTrack.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C22A1823923100416A4E /* MP42ChapterTrack.m */; }; + A9B9C2761823923200416A4E /* MP42ClosedCaptionTrack.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C22B1823923100416A4E /* MP42ClosedCaptionTrack.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C2771823923200416A4E /* MP42ClosedCaptionTrack.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C22C1823923100416A4E /* MP42ClosedCaptionTrack.m */; }; + A9B9C2781823923200416A4E /* MP42ConverterProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C22D1823923100416A4E /* MP42ConverterProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C2791823923200416A4E /* MP42Fifo.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C22E1823923100416A4E /* MP42Fifo.h */; }; + A9B9C27A1823923200416A4E /* MP42Fifo.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C22F1823923100416A4E /* MP42Fifo.m */; }; + A9B9C27B1823923200416A4E /* MP42File.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2301823923100416A4E /* MP42File.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C27C1823923200416A4E /* MP42File.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2311823923100416A4E /* MP42File.m */; }; + A9B9C27D1823923200416A4E /* MP42FileImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2321823923100416A4E /* MP42FileImporter.h */; }; + A9B9C27E1823923200416A4E /* MP42FileImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2331823923100416A4E /* MP42FileImporter.m */; }; + A9B9C27F1823923200416A4E /* MP42H264Importer.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2341823923100416A4E /* MP42H264Importer.h */; }; + A9B9C2801823923200416A4E /* MP42H264Importer.mm in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2351823923100416A4E /* MP42H264Importer.mm */; }; + A9B9C2811823923200416A4E /* MP42HtmlParser.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2361823923100416A4E /* MP42HtmlParser.h */; }; + A9B9C2821823923200416A4E /* MP42HtmlParser.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2371823923100416A4E /* MP42HtmlParser.m */; }; + A9B9C2831823923200416A4E /* MP42Image.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2381823923100416A4E /* MP42Image.h */; }; + A9B9C2841823923200416A4E /* MP42Image.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2391823923100416A4E /* MP42Image.m */; }; + A9B9C2851823923200416A4E /* MP42MediaFormat.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C23A1823923100416A4E /* MP42MediaFormat.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C2861823923200416A4E /* MP42MediaFormat.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C23B1823923100416A4E /* MP42MediaFormat.m */; }; + A9B9C2871823923200416A4E /* MP42Metadata.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C23C1823923100416A4E /* MP42Metadata.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C2881823923200416A4E /* MP42Metadata.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C23D1823923100416A4E /* MP42Metadata.m */; }; + A9B9C2891823923200416A4E /* MP42MkvImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C23E1823923100416A4E /* MP42MkvImporter.h */; }; + A9B9C28A1823923200416A4E /* MP42MkvImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C23F1823923100416A4E /* MP42MkvImporter.m */; }; + A9B9C28B1823923200416A4E /* MP42Mp4Importer.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2401823923100416A4E /* MP42Mp4Importer.h */; }; + A9B9C28C1823923200416A4E /* MP42Mp4Importer.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2411823923100416A4E /* MP42Mp4Importer.m */; }; + A9B9C28D1823923200416A4E /* MP42Muxer.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2421823923100416A4E /* MP42Muxer.h */; }; + A9B9C28E1823923200416A4E /* MP42Muxer.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2431823923100416A4E /* MP42Muxer.m */; }; + A9B9C28F1823923200416A4E /* MP42OCRWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2441823923100416A4E /* MP42OCRWrapper.h */; }; + A9B9C2901823923200416A4E /* MP42OCRWrapper.mm in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2451823923100416A4E /* MP42OCRWrapper.mm */; }; + A9B9C2911823923200416A4E /* MP42QTImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2461823923100416A4E /* MP42QTImporter.h */; }; + A9B9C2921823923200416A4E /* MP42QTImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2471823923100416A4E /* MP42QTImporter.m */; }; + A9B9C2931823923200416A4E /* MP42Sample.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2481823923100416A4E /* MP42Sample.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C2941823923200416A4E /* MP42Sample.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2491823923100416A4E /* MP42Sample.m */; }; + A9B9C2951823923200416A4E /* MP42SrtImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C24A1823923100416A4E /* MP42SrtImporter.h */; }; + A9B9C2961823923200416A4E /* MP42SrtImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C24B1823923100416A4E /* MP42SrtImporter.m */; }; + A9B9C2971823923200416A4E /* MP42SubtitleTrack.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C24C1823923100416A4E /* MP42SubtitleTrack.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C2981823923200416A4E /* MP42SubtitleTrack.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C24D1823923100416A4E /* MP42SubtitleTrack.m */; }; + A9B9C2991823923200416A4E /* MP42SubUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C24E1823923100416A4E /* MP42SubUtilities.h */; }; + A9B9C29A1823923200416A4E /* MP42SubUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C24F1823923100416A4E /* MP42SubUtilities.m */; }; + A9B9C29B1823923200416A4E /* MP42Track.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2501823923100416A4E /* MP42Track.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C29C1823923200416A4E /* MP42Track.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2511823923100416A4E /* MP42Track.m */; }; + A9B9C29D1823923200416A4E /* MP42Utilities.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2521823923100416A4E /* MP42Utilities.h */; }; + A9B9C29E1823923200416A4E /* MP42Utilities.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2531823923100416A4E /* MP42Utilities.m */; }; + A9B9C29F1823923200416A4E /* MP42VideoTrack.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2541823923100416A4E /* MP42VideoTrack.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A9B9C2A01823923200416A4E /* MP42VideoTrack.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2551823923100416A4E /* MP42VideoTrack.m */; }; + A9B9C2A11823923200416A4E /* MP42VobSubImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2561823923200416A4E /* MP42VobSubImporter.h */; }; + A9B9C2A21823923200416A4E /* MP42VobSubImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2571823923200416A4E /* MP42VobSubImporter.m */; }; + A9B9C2A31823923200416A4E /* MP42XMLReader.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2581823923200416A4E /* MP42XMLReader.h */; }; + A9B9C2A41823923200416A4E /* MP42XMLReader.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2591823923200416A4E /* MP42XMLReader.m */; }; + A9B9C2A51823923200416A4E /* downmix.c in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C25B1823923200416A4E /* downmix.c */; }; + A9B9C2A61823923200416A4E /* downmix.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C25C1823923200416A4E /* downmix.h */; }; + A9B9C2A71823923200416A4E /* MatroskaFile.c in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C25D1823923200416A4E /* MatroskaFile.c */; }; + A9B9C2A81823923200416A4E /* MatroskaFile.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C25E1823923200416A4E /* MatroskaFile.h */; }; + A9B9C2A91823923200416A4E /* MatroskaParser.c in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C25F1823923200416A4E /* MatroskaParser.c */; }; + A9B9C2AA1823923200416A4E /* MatroskaParser.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2601823923200416A4E /* MatroskaParser.h */; }; + A9B9C2AB1823923200416A4E /* mbs.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2611823923200416A4E /* mbs.cpp */; }; + A9B9C2AC1823923200416A4E /* mbs.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2621823923200416A4E /* mbs.h */; }; + A9B9C2AD1823923200416A4E /* mpeg4ip_bitstream.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2631823923200416A4E /* mpeg4ip_bitstream.h */; }; + A9B9C2AE1823923200416A4E /* sfifo.c in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2641823923200416A4E /* sfifo.c */; }; + A9B9C2AF1823923200416A4E /* sfifo.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2651823923200416A4E /* sfifo.h */; }; + A9B9C2B3182393ED00416A4E /* libmp4v2.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C2B2182393ED00416A4E /* libmp4v2.a */; }; + A9B9C2C41823957800416A4E /* SBLanguages.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2C21823957800416A4E /* SBLanguages.h */; }; + A9B9C2C51823957800416A4E /* SBLanguages.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2C31823957800416A4E /* SBLanguages.m */; }; + A9B9C2C81823962600416A4E /* UniversalDetector.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2C71823962600416A4E /* UniversalDetector.h */; }; + A9B9C2CB1823968400416A4E /* RegexKitLite.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2C91823968400416A4E /* RegexKitLite.h */; }; + A9B9C2CC1823968400416A4E /* RegexKitLite.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2CA1823968400416A4E /* RegexKitLite.m */; }; + A9B9C2CF182396A100416A4E /* SBRatings.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2CD182396A100416A4E /* SBRatings.h */; }; + A9B9C2D0182396A100416A4E /* SBRatings.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2CE182396A100416A4E /* SBRatings.m */; }; + A9B9C2D3182396C400416A4E /* JSONKit.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2D1182396C400416A4E /* JSONKit.h */; }; + A9B9C2D4182396C400416A4E /* JSONKit.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2D2182396C400416A4E /* JSONKit.m */; }; + A9B9C2D6182396FB00416A4E /* baseapi.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2D5182396FB00416A4E /* baseapi.h */; }; + A9B9C2D81823970E00416A4E /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C2D71823970E00416A4E /* AVFoundation.framework */; settings = {ATTRIBUTES = (Weak, ); }; }; + A9B9C2DA1823971F00416A4E /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C2D91823971F00416A4E /* AudioToolbox.framework */; }; + A9B9C2DC1823972400416A4E /* QTKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C2DB1823972400416A4E /* QTKit.framework */; }; + A9B9C2DE1823973200416A4E /* CoreMedia.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C2DD1823973200416A4E /* CoreMedia.framework */; settings = {ATTRIBUTES = (Weak, ); }; }; + A9B9C2E0182397D400416A4E /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C2DF182397D400416A4E /* libz.dylib */; }; + A9B9C2E2182397DD00416A4E /* libbz2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C2E1182397DD00416A4E /* libbz2.dylib */; }; + A9B9C2E3182397E700416A4E /* libuniversaldetector.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C2C11823944700416A4E /* libuniversaldetector.a */; }; + A9B9C2E5182397F100416A4E /* libicucore.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C2E4182397F100416A4E /* libicucore.dylib */; }; + A9B9C4931823986200416A4E /* Quartz.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C4921823986200416A4E /* Quartz.framework */; }; + A9B9C4981823989300416A4E /* libavcodec.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C4941823989200416A4E /* libavcodec.a */; }; + A9B9C4991823989300416A4E /* libavdevice.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C4951823989200416A4E /* libavdevice.a */; }; + A9B9C49A1823989300416A4E /* libavformat.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C4961823989300416A4E /* libavformat.a */; }; + A9B9C49B1823989300416A4E /* libavutil.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C4971823989300416A4E /* libavutil.a */; }; + A9B9C49F1823989C00416A4E /* libjpeg.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C49C1823989C00416A4E /* libjpeg.a */; }; + A9B9C4A01823989C00416A4E /* liblept.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C49D1823989C00416A4E /* liblept.a */; }; + A9B9C4A11823989C00416A4E /* libtesseract.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A9B9C49E1823989C00416A4E /* libtesseract.a */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -25,6 +125,27 @@ remoteGlobalIDString = A9B9C1EC182391DF00416A4E; remoteInfo = MP42; }; + A9B9C2BC1823944700416A4E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A9B9C2B61823944700416A4E /* UniversalDetector.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 8DC2EF5B0486A6940098B216; + remoteInfo = UniversalDetector; + }; + A9B9C2BE1823944700416A4E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A9B9C2B61823944700416A4E /* UniversalDetector.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1B0DDCAB0A2D0AD10009B697; + remoteInfo = DetectorTest; + }; + A9B9C2C01823944700416A4E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A9B9C2B61823944700416A4E /* UniversalDetector.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3DBF4F570BCD396800DA401A; + remoteInfo = universaldetector; + }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ @@ -36,13 +157,112 @@ A9B9C1F8182391DF00416A4E /* MP42-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "MP42-Info.plist"; sourceTree = ""; }; A9B9C1FA182391DF00416A4E /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; A9B9C1FC182391DF00416A4E /* MP42-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "MP42-Prefix.pch"; sourceTree = ""; }; - A9B9C1FD182391DF00416A4E /* MP42.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MP42.h; sourceTree = ""; }; - A9B9C1FE182391DF00416A4E /* MP42.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MP42.m; sourceTree = ""; }; A9B9C204182391DF00416A4E /* MP42Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = MP42Tests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; A9B9C205182391DF00416A4E /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; A9B9C20D182391DF00416A4E /* MP42Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "MP42Tests-Info.plist"; sourceTree = ""; }; A9B9C20F182391DF00416A4E /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; A9B9C211182391DF00416A4E /* MP42Tests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MP42Tests.m; sourceTree = ""; }; + A9B9C21B1823923100416A4E /* MP42AACImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42AACImporter.h; sourceTree = ""; }; + A9B9C21C1823923100416A4E /* MP42AACImporter.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MP42AACImporter.mm; sourceTree = ""; }; + A9B9C21D1823923100416A4E /* MP42AC3Importer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42AC3Importer.h; sourceTree = ""; }; + A9B9C21E1823923100416A4E /* MP42AC3Importer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42AC3Importer.m; sourceTree = ""; }; + A9B9C21F1823923100416A4E /* MP42AudioConverter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42AudioConverter.h; sourceTree = ""; }; + A9B9C2201823923100416A4E /* MP42AudioConverter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42AudioConverter.m; sourceTree = ""; }; + A9B9C2211823923100416A4E /* MP42AudioTrack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42AudioTrack.h; sourceTree = ""; }; + A9B9C2221823923100416A4E /* MP42AudioTrack.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42AudioTrack.m; sourceTree = ""; }; + A9B9C2231823923100416A4E /* MP42AVFImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42AVFImporter.h; sourceTree = ""; }; + A9B9C2241823923100416A4E /* MP42AVFImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42AVFImporter.m; sourceTree = ""; }; + A9B9C2251823923100416A4E /* MP42BitmapSubConverter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42BitmapSubConverter.h; sourceTree = ""; }; + A9B9C2261823923100416A4E /* MP42BitmapSubConverter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42BitmapSubConverter.m; sourceTree = ""; }; + A9B9C2271823923100416A4E /* MP42CCImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42CCImporter.h; sourceTree = ""; }; + A9B9C2281823923100416A4E /* MP42CCImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42CCImporter.m; sourceTree = ""; }; + A9B9C2291823923100416A4E /* MP42ChapterTrack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42ChapterTrack.h; sourceTree = ""; }; + A9B9C22A1823923100416A4E /* MP42ChapterTrack.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42ChapterTrack.m; sourceTree = ""; }; + A9B9C22B1823923100416A4E /* MP42ClosedCaptionTrack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42ClosedCaptionTrack.h; sourceTree = ""; }; + A9B9C22C1823923100416A4E /* MP42ClosedCaptionTrack.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42ClosedCaptionTrack.m; sourceTree = ""; }; + A9B9C22D1823923100416A4E /* MP42ConverterProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42ConverterProtocol.h; sourceTree = ""; }; + A9B9C22E1823923100416A4E /* MP42Fifo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Fifo.h; sourceTree = ""; }; + A9B9C22F1823923100416A4E /* MP42Fifo.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Fifo.m; sourceTree = ""; }; + A9B9C2301823923100416A4E /* MP42File.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42File.h; sourceTree = ""; }; + A9B9C2311823923100416A4E /* MP42File.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42File.m; sourceTree = ""; }; + A9B9C2321823923100416A4E /* MP42FileImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42FileImporter.h; sourceTree = ""; }; + A9B9C2331823923100416A4E /* MP42FileImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42FileImporter.m; sourceTree = ""; }; + A9B9C2341823923100416A4E /* MP42H264Importer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42H264Importer.h; sourceTree = ""; }; + A9B9C2351823923100416A4E /* MP42H264Importer.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MP42H264Importer.mm; sourceTree = ""; }; + A9B9C2361823923100416A4E /* MP42HtmlParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42HtmlParser.h; sourceTree = ""; }; + A9B9C2371823923100416A4E /* MP42HtmlParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42HtmlParser.m; sourceTree = ""; }; + A9B9C2381823923100416A4E /* MP42Image.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Image.h; sourceTree = ""; }; + A9B9C2391823923100416A4E /* MP42Image.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Image.m; sourceTree = ""; }; + A9B9C23A1823923100416A4E /* MP42MediaFormat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MediaFormat.h; sourceTree = ""; }; + A9B9C23B1823923100416A4E /* MP42MediaFormat.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MediaFormat.m; sourceTree = ""; }; + A9B9C23C1823923100416A4E /* MP42Metadata.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Metadata.h; sourceTree = ""; }; + A9B9C23D1823923100416A4E /* MP42Metadata.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Metadata.m; sourceTree = ""; }; + A9B9C23E1823923100416A4E /* MP42MkvImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvImporter.h; sourceTree = ""; }; + A9B9C23F1823923100416A4E /* MP42MkvImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvImporter.m; sourceTree = ""; }; + A9B9C2401823923100416A4E /* MP42Mp4Importer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Mp4Importer.h; sourceTree = ""; }; + A9B9C2411823923100416A4E /* MP42Mp4Importer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Mp4Importer.m; sourceTree = ""; }; + A9B9C2421823923100416A4E /* MP42Muxer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Muxer.h; sourceTree = ""; }; + A9B9C2431823923100416A4E /* MP42Muxer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Muxer.m; sourceTree = ""; }; + A9B9C2441823923100416A4E /* MP42OCRWrapper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42OCRWrapper.h; sourceTree = ""; }; + A9B9C2451823923100416A4E /* MP42OCRWrapper.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MP42OCRWrapper.mm; sourceTree = ""; }; + A9B9C2461823923100416A4E /* MP42QTImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42QTImporter.h; sourceTree = ""; }; + A9B9C2471823923100416A4E /* MP42QTImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42QTImporter.m; sourceTree = ""; }; + A9B9C2481823923100416A4E /* MP42Sample.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Sample.h; sourceTree = ""; }; + A9B9C2491823923100416A4E /* MP42Sample.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Sample.m; sourceTree = ""; }; + A9B9C24A1823923100416A4E /* MP42SrtImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42SrtImporter.h; sourceTree = ""; }; + A9B9C24B1823923100416A4E /* MP42SrtImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42SrtImporter.m; sourceTree = ""; }; + A9B9C24C1823923100416A4E /* MP42SubtitleTrack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42SubtitleTrack.h; sourceTree = ""; }; + A9B9C24D1823923100416A4E /* MP42SubtitleTrack.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42SubtitleTrack.m; sourceTree = ""; }; + A9B9C24E1823923100416A4E /* MP42SubUtilities.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42SubUtilities.h; sourceTree = ""; }; + A9B9C24F1823923100416A4E /* MP42SubUtilities.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42SubUtilities.m; sourceTree = ""; }; + A9B9C2501823923100416A4E /* MP42Track.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Track.h; sourceTree = ""; }; + A9B9C2511823923100416A4E /* MP42Track.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Track.m; sourceTree = ""; }; + A9B9C2521823923100416A4E /* MP42Utilities.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Utilities.h; sourceTree = ""; }; + A9B9C2531823923100416A4E /* MP42Utilities.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Utilities.m; sourceTree = ""; }; + A9B9C2541823923100416A4E /* MP42VideoTrack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42VideoTrack.h; sourceTree = ""; }; + A9B9C2551823923100416A4E /* MP42VideoTrack.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42VideoTrack.m; sourceTree = ""; }; + A9B9C2561823923200416A4E /* MP42VobSubImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42VobSubImporter.h; sourceTree = ""; }; + A9B9C2571823923200416A4E /* MP42VobSubImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42VobSubImporter.m; sourceTree = ""; }; + A9B9C2581823923200416A4E /* MP42XMLReader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42XMLReader.h; sourceTree = ""; }; + A9B9C2591823923200416A4E /* MP42XMLReader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42XMLReader.m; sourceTree = ""; }; + A9B9C25B1823923200416A4E /* downmix.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = downmix.c; sourceTree = ""; }; + A9B9C25C1823923200416A4E /* downmix.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = downmix.h; sourceTree = ""; }; + A9B9C25D1823923200416A4E /* MatroskaFile.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = MatroskaFile.c; sourceTree = ""; }; + A9B9C25E1823923200416A4E /* MatroskaFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MatroskaFile.h; sourceTree = ""; }; + A9B9C25F1823923200416A4E /* MatroskaParser.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = MatroskaParser.c; sourceTree = ""; }; + A9B9C2601823923200416A4E /* MatroskaParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MatroskaParser.h; sourceTree = ""; }; + A9B9C2611823923200416A4E /* mbs.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = mbs.cpp; sourceTree = ""; }; + A9B9C2621823923200416A4E /* mbs.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mbs.h; sourceTree = ""; }; + A9B9C2631823923200416A4E /* mpeg4ip_bitstream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mpeg4ip_bitstream.h; sourceTree = ""; }; + A9B9C2641823923200416A4E /* sfifo.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sfifo.c; sourceTree = ""; }; + A9B9C2651823923200416A4E /* sfifo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sfifo.h; sourceTree = ""; }; + A9B9C2B2182393ED00416A4E /* libmp4v2.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libmp4v2.a; path = mp4v2/libmp4v2.a; sourceTree = ""; }; + A9B9C2B61823944700416A4E /* UniversalDetector.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = UniversalDetector.xcodeproj; path = UniversalDetector/UniversalDetector.xcodeproj; sourceTree = ""; }; + A9B9C2C21823957800416A4E /* SBLanguages.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SBLanguages.h; sourceTree = ""; }; + A9B9C2C31823957800416A4E /* SBLanguages.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SBLanguages.m; sourceTree = ""; }; + A9B9C2C71823962600416A4E /* UniversalDetector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = UniversalDetector.h; path = UniversalDetector/UniversalDetector.h; sourceTree = SOURCE_ROOT; }; + A9B9C2C91823968400416A4E /* RegexKitLite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RegexKitLite.h; sourceTree = ""; }; + A9B9C2CA1823968400416A4E /* RegexKitLite.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RegexKitLite.m; sourceTree = ""; }; + A9B9C2CD182396A100416A4E /* SBRatings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SBRatings.h; sourceTree = ""; }; + A9B9C2CE182396A100416A4E /* SBRatings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SBRatings.m; sourceTree = ""; }; + A9B9C2D1182396C400416A4E /* JSONKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSONKit.h; sourceTree = ""; }; + A9B9C2D2182396C400416A4E /* JSONKit.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = ""; }; + A9B9C2D5182396FB00416A4E /* baseapi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = baseapi.h; path = Tesseract/include/tesseract/baseapi.h; sourceTree = SOURCE_ROOT; }; + A9B9C2D71823970E00416A4E /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; + A9B9C2D91823971F00416A4E /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; + A9B9C2DB1823972400416A4E /* QTKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QTKit.framework; path = System/Library/Frameworks/QTKit.framework; sourceTree = SDKROOT; }; + A9B9C2DD1823973200416A4E /* CoreMedia.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMedia.framework; path = System/Library/Frameworks/CoreMedia.framework; sourceTree = SDKROOT; }; + A9B9C2DF182397D400416A4E /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; }; + A9B9C2E1182397DD00416A4E /* libbz2.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libbz2.dylib; path = usr/lib/libbz2.dylib; sourceTree = SDKROOT; }; + A9B9C2E4182397F100416A4E /* libicucore.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libicucore.dylib; path = usr/lib/libicucore.dylib; sourceTree = SDKROOT; }; + A9B9C4921823986200416A4E /* Quartz.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Quartz.framework; path = System/Library/Frameworks/Quartz.framework; sourceTree = SDKROOT; }; + A9B9C4941823989200416A4E /* libavcodec.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libavcodec.a; path = ffmpeg/lib/libavcodec.a; sourceTree = ""; }; + A9B9C4951823989200416A4E /* libavdevice.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libavdevice.a; path = ffmpeg/lib/libavdevice.a; sourceTree = ""; }; + A9B9C4961823989300416A4E /* libavformat.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libavformat.a; path = ffmpeg/lib/libavformat.a; sourceTree = ""; }; + A9B9C4971823989300416A4E /* libavutil.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libavutil.a; path = ffmpeg/lib/libavutil.a; sourceTree = ""; }; + A9B9C49C1823989C00416A4E /* libjpeg.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libjpeg.a; path = Tesseract/lib/libjpeg.a; sourceTree = ""; }; + A9B9C49D1823989C00416A4E /* liblept.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = liblept.a; path = Tesseract/lib/liblept.a; sourceTree = ""; }; + A9B9C49E1823989C00416A4E /* libtesseract.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libtesseract.a; path = Tesseract/lib/libtesseract.a; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -50,6 +270,23 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + A9B9C49F1823989C00416A4E /* libjpeg.a in Frameworks */, + A9B9C4A01823989C00416A4E /* liblept.a in Frameworks */, + A9B9C4A11823989C00416A4E /* libtesseract.a in Frameworks */, + A9B9C4981823989300416A4E /* libavcodec.a in Frameworks */, + A9B9C4991823989300416A4E /* libavdevice.a in Frameworks */, + A9B9C49A1823989300416A4E /* libavformat.a in Frameworks */, + A9B9C49B1823989300416A4E /* libavutil.a in Frameworks */, + A9B9C4931823986200416A4E /* Quartz.framework in Frameworks */, + A9B9C2E5182397F100416A4E /* libicucore.dylib in Frameworks */, + A9B9C2E3182397E700416A4E /* libuniversaldetector.a in Frameworks */, + A9B9C2E2182397DD00416A4E /* libbz2.dylib in Frameworks */, + A9B9C2E0182397D400416A4E /* libz.dylib in Frameworks */, + A9B9C2B3182393ED00416A4E /* libmp4v2.a in Frameworks */, + A9B9C2DC1823972400416A4E /* QTKit.framework in Frameworks */, + A9B9C2DA1823971F00416A4E /* AudioToolbox.framework in Frameworks */, + A9B9C2D81823970E00416A4E /* AVFoundation.framework in Frameworks */, + A9B9C2DE1823973200416A4E /* CoreMedia.framework in Frameworks */, A9B9C1F1182391DF00416A4E /* Cocoa.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -89,6 +326,23 @@ A9B9C1EF182391DF00416A4E /* Frameworks */ = { isa = PBXGroup; children = ( + A9B9C2B2182393ED00416A4E /* libmp4v2.a */, + A9B9C49C1823989C00416A4E /* libjpeg.a */, + A9B9C49D1823989C00416A4E /* liblept.a */, + A9B9C49E1823989C00416A4E /* libtesseract.a */, + A9B9C4941823989200416A4E /* libavcodec.a */, + A9B9C4951823989200416A4E /* libavdevice.a */, + A9B9C4961823989300416A4E /* libavformat.a */, + A9B9C4971823989300416A4E /* libavutil.a */, + A9B9C2E4182397F100416A4E /* libicucore.dylib */, + A9B9C2E1182397DD00416A4E /* libbz2.dylib */, + A9B9C2DF182397D400416A4E /* libz.dylib */, + A9B9C4921823986200416A4E /* Quartz.framework */, + A9B9C2DD1823973200416A4E /* CoreMedia.framework */, + A9B9C2DB1823972400416A4E /* QTKit.framework */, + A9B9C2D91823971F00416A4E /* AudioToolbox.framework */, + A9B9C2D71823970E00416A4E /* AVFoundation.framework */, + A9B9C2B61823944700416A4E /* UniversalDetector.xcodeproj */, A9B9C1F0182391DF00416A4E /* Cocoa.framework */, A9B9C205182391DF00416A4E /* XCTest.framework */, A9B9C1F2182391DF00416A4E /* Other Frameworks */, @@ -109,8 +363,26 @@ A9B9C1F6182391DF00416A4E /* MP42 */ = { isa = PBXGroup; children = ( - A9B9C1FD182391DF00416A4E /* MP42.h */, - A9B9C1FE182391DF00416A4E /* MP42.m */, + A9B9C2301823923100416A4E /* MP42File.h */, + A9B9C2311823923100416A4E /* MP42File.m */, + A9B9C2501823923100416A4E /* MP42Track.h */, + A9B9C2511823923100416A4E /* MP42Track.m */, + A9B9C2541823923100416A4E /* MP42VideoTrack.h */, + A9B9C2551823923100416A4E /* MP42VideoTrack.m */, + A9B9C2211823923100416A4E /* MP42AudioTrack.h */, + A9B9C2221823923100416A4E /* MP42AudioTrack.m */, + A9B9C2291823923100416A4E /* MP42ChapterTrack.h */, + A9B9C22A1823923100416A4E /* MP42ChapterTrack.m */, + A9B9C24C1823923100416A4E /* MP42SubtitleTrack.h */, + A9B9C24D1823923100416A4E /* MP42SubtitleTrack.m */, + A9B9C22B1823923100416A4E /* MP42ClosedCaptionTrack.h */, + A9B9C22C1823923100416A4E /* MP42ClosedCaptionTrack.m */, + A9B9C23C1823923100416A4E /* MP42Metadata.h */, + A9B9C23D1823923100416A4E /* MP42Metadata.m */, + A9B9C23A1823923100416A4E /* MP42MediaFormat.h */, + A9B9C23B1823923100416A4E /* MP42MediaFormat.m */, + A9B9C4A418239B7E00416A4E /* Utility */, + A9B9C4A218239B6F00416A4E /* Muxer */, A9B9C1F7182391DF00416A4E /* Supporting Files */, ); path = MP42; @@ -144,6 +416,121 @@ name = "Supporting Files"; sourceTree = ""; }; + A9B9C25A1823923200416A4E /* others */ = { + isa = PBXGroup; + children = ( + A9B9C25B1823923200416A4E /* downmix.c */, + A9B9C25C1823923200416A4E /* downmix.h */, + A9B9C25D1823923200416A4E /* MatroskaFile.c */, + A9B9C25E1823923200416A4E /* MatroskaFile.h */, + A9B9C25F1823923200416A4E /* MatroskaParser.c */, + A9B9C2601823923200416A4E /* MatroskaParser.h */, + A9B9C2611823923200416A4E /* mbs.cpp */, + A9B9C2621823923200416A4E /* mbs.h */, + A9B9C2631823923200416A4E /* mpeg4ip_bitstream.h */, + ); + name = others; + path = muxer; + sourceTree = ""; + }; + A9B9C2B71823944700416A4E /* Products */ = { + isa = PBXGroup; + children = ( + A9B9C2BD1823944700416A4E /* UniversalDetector.framework */, + A9B9C2BF1823944700416A4E /* DetectorTest */, + A9B9C2C11823944700416A4E /* libuniversaldetector.a */, + ); + name = Products; + sourceTree = ""; + }; + A9B9C4A218239B6F00416A4E /* Muxer */ = { + isa = PBXGroup; + children = ( + A9B9C2421823923100416A4E /* MP42Muxer.h */, + A9B9C2431823923100416A4E /* MP42Muxer.m */, + A9B9C2481823923100416A4E /* MP42Sample.h */, + A9B9C2491823923100416A4E /* MP42Sample.m */, + A9B9C22D1823923100416A4E /* MP42ConverterProtocol.h */, + A9B9C22E1823923100416A4E /* MP42Fifo.h */, + A9B9C22F1823923100416A4E /* MP42Fifo.m */, + A9B9C2321823923100416A4E /* MP42FileImporter.h */, + A9B9C2331823923100416A4E /* MP42FileImporter.m */, + A9B9C4A518239BE900416A4E /* converters */, + A9B9C4A318239B7600416A4E /* Importers */, + A9B9C25A1823923200416A4E /* others */, + ); + name = Muxer; + sourceTree = ""; + }; + A9B9C4A318239B7600416A4E /* Importers */ = { + isa = PBXGroup; + children = ( + A9B9C2341823923100416A4E /* MP42H264Importer.h */, + A9B9C2351823923100416A4E /* MP42H264Importer.mm */, + A9B9C2561823923200416A4E /* MP42VobSubImporter.h */, + A9B9C2571823923200416A4E /* MP42VobSubImporter.m */, + A9B9C23E1823923100416A4E /* MP42MkvImporter.h */, + A9B9C23F1823923100416A4E /* MP42MkvImporter.m */, + A9B9C2401823923100416A4E /* MP42Mp4Importer.h */, + A9B9C2411823923100416A4E /* MP42Mp4Importer.m */, + A9B9C2461823923100416A4E /* MP42QTImporter.h */, + A9B9C2471823923100416A4E /* MP42QTImporter.m */, + A9B9C24A1823923100416A4E /* MP42SrtImporter.h */, + A9B9C24B1823923100416A4E /* MP42SrtImporter.m */, + A9B9C2231823923100416A4E /* MP42AVFImporter.h */, + A9B9C2241823923100416A4E /* MP42AVFImporter.m */, + A9B9C2271823923100416A4E /* MP42CCImporter.h */, + A9B9C2281823923100416A4E /* MP42CCImporter.m */, + A9B9C21B1823923100416A4E /* MP42AACImporter.h */, + A9B9C21C1823923100416A4E /* MP42AACImporter.mm */, + A9B9C21D1823923100416A4E /* MP42AC3Importer.h */, + A9B9C21E1823923100416A4E /* MP42AC3Importer.m */, + ); + name = Importers; + sourceTree = ""; + }; + A9B9C4A418239B7E00416A4E /* Utility */ = { + isa = PBXGroup; + children = ( + A9B9C2521823923100416A4E /* MP42Utilities.h */, + A9B9C2531823923100416A4E /* MP42Utilities.m */, + A9B9C24E1823923100416A4E /* MP42SubUtilities.h */, + A9B9C24F1823923100416A4E /* MP42SubUtilities.m */, + A9B9C2581823923200416A4E /* MP42XMLReader.h */, + A9B9C2591823923200416A4E /* MP42XMLReader.m */, + A9B9C2361823923100416A4E /* MP42HtmlParser.h */, + A9B9C2371823923100416A4E /* MP42HtmlParser.m */, + A9B9C2381823923100416A4E /* MP42Image.h */, + A9B9C2391823923100416A4E /* MP42Image.m */, + A9B9C2C91823968400416A4E /* RegexKitLite.h */, + A9B9C2CA1823968400416A4E /* RegexKitLite.m */, + A9B9C2CD182396A100416A4E /* SBRatings.h */, + A9B9C2CE182396A100416A4E /* SBRatings.m */, + A9B9C2D1182396C400416A4E /* JSONKit.h */, + A9B9C2D2182396C400416A4E /* JSONKit.m */, + A9B9C2D5182396FB00416A4E /* baseapi.h */, + A9B9C2C71823962600416A4E /* UniversalDetector.h */, + A9B9C2C21823957800416A4E /* SBLanguages.h */, + A9B9C2C31823957800416A4E /* SBLanguages.m */, + ); + name = Utility; + sourceTree = ""; + }; + A9B9C4A518239BE900416A4E /* converters */ = { + isa = PBXGroup; + children = ( + A9B9C2641823923200416A4E /* sfifo.c */, + A9B9C2651823923200416A4E /* sfifo.h */, + A9B9C2441823923100416A4E /* MP42OCRWrapper.h */, + A9B9C2451823923100416A4E /* MP42OCRWrapper.mm */, + A9B9C2251823923100416A4E /* MP42BitmapSubConverter.h */, + A9B9C2261823923100416A4E /* MP42BitmapSubConverter.m */, + A9B9C21F1823923100416A4E /* MP42AudioConverter.h */, + A9B9C2201823923100416A4E /* MP42AudioConverter.m */, + ); + name = converters; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ @@ -151,6 +538,50 @@ isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( + A9B9C27B1823923200416A4E /* MP42File.h in Headers */, + A9B9C29B1823923200416A4E /* MP42Track.h in Headers */, + A9B9C29F1823923200416A4E /* MP42VideoTrack.h in Headers */, + A9B9C26C1823923200416A4E /* MP42AudioTrack.h in Headers */, + A9B9C2741823923200416A4E /* MP42ChapterTrack.h in Headers */, + A9B9C2971823923200416A4E /* MP42SubtitleTrack.h in Headers */, + A9B9C2761823923200416A4E /* MP42ClosedCaptionTrack.h in Headers */, + A9B9C2871823923200416A4E /* MP42Metadata.h in Headers */, + A9B9C2851823923200416A4E /* MP42MediaFormat.h in Headers */, + A9B9C2781823923200416A4E /* MP42ConverterProtocol.h in Headers */, + A9B9C2931823923200416A4E /* MP42Sample.h in Headers */, + A9B9C2911823923200416A4E /* MP42QTImporter.h in Headers */, + A9B9C28F1823923200416A4E /* MP42OCRWrapper.h in Headers */, + A9B9C2811823923200416A4E /* MP42HtmlParser.h in Headers */, + A9B9C2A61823923200416A4E /* downmix.h in Headers */, + A9B9C2AA1823923200416A4E /* MatroskaParser.h in Headers */, + A9B9C27D1823923200416A4E /* MP42FileImporter.h in Headers */, + A9B9C26E1823923200416A4E /* MP42AVFImporter.h in Headers */, + A9B9C2791823923200416A4E /* MP42Fifo.h in Headers */, + A9B9C2CF182396A100416A4E /* SBRatings.h in Headers */, + A9B9C2C41823957800416A4E /* SBLanguages.h in Headers */, + A9B9C2A31823923200416A4E /* MP42XMLReader.h in Headers */, + A9B9C2CB1823968400416A4E /* RegexKitLite.h in Headers */, + A9B9C28D1823923200416A4E /* MP42Muxer.h in Headers */, + A9B9C2831823923200416A4E /* MP42Image.h in Headers */, + A9B9C2AD1823923200416A4E /* mpeg4ip_bitstream.h in Headers */, + A9B9C2A81823923200416A4E /* MatroskaFile.h in Headers */, + A9B9C2D6182396FB00416A4E /* baseapi.h in Headers */, + A9B9C2991823923200416A4E /* MP42SubUtilities.h in Headers */, + A9B9C28B1823923200416A4E /* MP42Mp4Importer.h in Headers */, + A9B9C2951823923200416A4E /* MP42SrtImporter.h in Headers */, + A9B9C2701823923200416A4E /* MP42BitmapSubConverter.h in Headers */, + A9B9C2721823923200416A4E /* MP42CCImporter.h in Headers */, + A9B9C2AF1823923200416A4E /* sfifo.h in Headers */, + A9B9C2C81823962600416A4E /* UniversalDetector.h in Headers */, + A9B9C27F1823923200416A4E /* MP42H264Importer.h in Headers */, + A9B9C2D3182396C400416A4E /* JSONKit.h in Headers */, + A9B9C29D1823923200416A4E /* MP42Utilities.h in Headers */, + A9B9C2661823923200416A4E /* MP42AACImporter.h in Headers */, + A9B9C2681823923200416A4E /* MP42AC3Importer.h in Headers */, + A9B9C26A1823923200416A4E /* MP42AudioConverter.h in Headers */, + A9B9C2A11823923200416A4E /* MP42VobSubImporter.h in Headers */, + A9B9C2AC1823923200416A4E /* mbs.h in Headers */, + A9B9C2891823923200416A4E /* MP42MkvImporter.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -213,10 +644,18 @@ hasScannedForEncodings = 0; knownRegions = ( en, + Base, + English, ); mainGroup = A9B9C1E3182391DF00416A4E; productRefGroup = A9B9C1EE182391DF00416A4E /* Products */; projectDirPath = ""; + projectReferences = ( + { + ProductGroup = A9B9C2B71823944700416A4E /* Products */; + ProjectRef = A9B9C2B61823944700416A4E /* UniversalDetector.xcodeproj */; + }, + ); projectRoot = ""; targets = ( A9B9C1EC182391DF00416A4E /* MP42 */, @@ -225,6 +664,30 @@ }; /* End PBXProject section */ +/* Begin PBXReferenceProxy section */ + A9B9C2BD1823944700416A4E /* UniversalDetector.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = UniversalDetector.framework; + remoteRef = A9B9C2BC1823944700416A4E /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + A9B9C2BF1823944700416A4E /* DetectorTest */ = { + isa = PBXReferenceProxy; + fileType = "compiled.mach-o.executable"; + path = DetectorTest; + remoteRef = A9B9C2BE1823944700416A4E /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + A9B9C2C11823944700416A4E /* libuniversaldetector.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libuniversaldetector.a; + remoteRef = A9B9C2C01823944700416A4E /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + /* Begin PBXResourcesBuildPhase section */ A9B9C1EB182391DF00416A4E /* Resources */ = { isa = PBXResourcesBuildPhase; @@ -249,7 +712,46 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - A9B9C1FF182391DF00416A4E /* MP42.m in Sources */, + A9B9C2A01823923200416A4E /* MP42VideoTrack.m in Sources */, + A9B9C27E1823923200416A4E /* MP42FileImporter.m in Sources */, + A9B9C27A1823923200416A4E /* MP42Fifo.m in Sources */, + A9B9C2801823923200416A4E /* MP42H264Importer.mm in Sources */, + A9B9C26B1823923200416A4E /* MP42AudioConverter.m in Sources */, + A9B9C2961823923200416A4E /* MP42SrtImporter.m in Sources */, + A9B9C2AB1823923200416A4E /* mbs.cpp in Sources */, + A9B9C2AE1823923200416A4E /* sfifo.c in Sources */, + A9B9C2921823923200416A4E /* MP42QTImporter.m in Sources */, + A9B9C2A21823923200416A4E /* MP42VobSubImporter.m in Sources */, + A9B9C28E1823923200416A4E /* MP42Muxer.m in Sources */, + A9B9C2D0182396A100416A4E /* SBRatings.m in Sources */, + A9B9C2691823923200416A4E /* MP42AC3Importer.m in Sources */, + A9B9C26F1823923200416A4E /* MP42AVFImporter.m in Sources */, + A9B9C2D4182396C400416A4E /* JSONKit.m in Sources */, + A9B9C27C1823923200416A4E /* MP42File.m in Sources */, + A9B9C2771823923200416A4E /* MP42ClosedCaptionTrack.m in Sources */, + A9B9C2A51823923200416A4E /* downmix.c in Sources */, + A9B9C2671823923200416A4E /* MP42AACImporter.mm in Sources */, + A9B9C2CC1823968400416A4E /* RegexKitLite.m in Sources */, + A9B9C2821823923200416A4E /* MP42HtmlParser.m in Sources */, + A9B9C2861823923200416A4E /* MP42MediaFormat.m in Sources */, + A9B9C2A41823923200416A4E /* MP42XMLReader.m in Sources */, + A9B9C2751823923200416A4E /* MP42ChapterTrack.m in Sources */, + A9B9C2C51823957800416A4E /* SBLanguages.m in Sources */, + A9B9C2841823923200416A4E /* MP42Image.m in Sources */, + A9B9C29E1823923200416A4E /* MP42Utilities.m in Sources */, + A9B9C28C1823923200416A4E /* MP42Mp4Importer.m in Sources */, + A9B9C26D1823923200416A4E /* MP42AudioTrack.m in Sources */, + A9B9C2901823923200416A4E /* MP42OCRWrapper.mm in Sources */, + A9B9C2881823923200416A4E /* MP42Metadata.m in Sources */, + A9B9C2A91823923200416A4E /* MatroskaParser.c in Sources */, + A9B9C2941823923200416A4E /* MP42Sample.m in Sources */, + A9B9C28A1823923200416A4E /* MP42MkvImporter.m in Sources */, + A9B9C2731823923200416A4E /* MP42CCImporter.m in Sources */, + A9B9C29A1823923200416A4E /* MP42SubUtilities.m in Sources */, + A9B9C2981823923200416A4E /* MP42SubtitleTrack.m in Sources */, + A9B9C29C1823923200416A4E /* MP42Track.m in Sources */, + A9B9C2711823923200416A4E /* MP42BitmapSubConverter.m in Sources */, + A9B9C2A71823923200416A4E /* MatroskaFile.c in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -295,9 +797,9 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_OBJC_ARC = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++98"; + CLANG_CXX_LIBRARY = "libstdc++"; + CLANG_ENABLE_OBJC_ARC = NO; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; @@ -316,15 +818,23 @@ "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.9; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, + "$(SRCROOT)/mp4v2/**", + "$(SRCROOT)/ffmpeg/**", + "$(SRCROOT)/Tesseract", + ); + MACOSX_DEPLOYMENT_TARGET = 10.6; ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; + SDKROOT = macosx10.8; + USER_HEADER_SEARCH_PATHS = ""; }; name = Debug; }; @@ -332,9 +842,9 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_OBJC_ARC = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++98"; + CLANG_CXX_LIBRARY = "libstdc++"; + CLANG_ENABLE_OBJC_ARC = NO; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; @@ -348,14 +858,22 @@ ENABLE_NS_ASSERTIONS = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.9; - SDKROOT = macosx; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, + "$(SRCROOT)/mp4v2/**", + "$(SRCROOT)/ffmpeg/**", + "$(SRCROOT)/Tesseract", + ); + MACOSX_DEPLOYMENT_TARGET = 10.6; + SDKROOT = macosx10.8; + USER_HEADER_SEARCH_PATHS = ""; }; name = Release; }; @@ -369,6 +887,12 @@ GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "MP42/MP42-Prefix.pch"; INFOPLIST_FILE = "MP42/MP42-Info.plist"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + /Users/damians/Desktop/MP42/mp4v2, + /Users/damians/Desktop/MP42/ffmpeg/lib, + /Users/damians/Desktop/MP42/Tesseract/lib, + ); PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = framework; }; @@ -384,6 +908,12 @@ GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "MP42/MP42-Prefix.pch"; INFOPLIST_FILE = "MP42/MP42-Info.plist"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + /Users/damians/Desktop/MP42/mp4v2, + /Users/damians/Desktop/MP42/ffmpeg/lib, + /Users/damians/Desktop/MP42/Tesseract/lib, + ); PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = framework; }; @@ -448,6 +978,7 @@ A9B9C217182391DF00416A4E /* Release */, ); defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; }; A9B9C218182391DF00416A4E /* Build configuration list for PBXNativeTarget "MP42Tests" */ = { isa = XCConfigurationList; @@ -456,6 +987,7 @@ A9B9C21A182391DF00416A4E /* Release */, ); defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; diff --git a/MP42/JSONKit.h b/MP42/JSONKit.h new file mode 100755 index 0000000..71bd0c3 --- /dev/null +++ b/MP42/JSONKit.h @@ -0,0 +1,251 @@ +// +// JSONKit.h +// http://github.com/johnezang/JSONKit +// Dual licensed under either the terms of the BSD License, or alternatively +// under the terms of the Apache License, Version 2.0, as specified below. +// + +/* + Copyright (c) 2011, John Engelhart + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the Zang Industries nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/* + Copyright 2011 John Engelhart + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#include +#include +#include +#include +#include + +#ifdef __OBJC__ +#import +#import +#import +#import +#import +#import +#endif // __OBJC__ + +#ifdef __cplusplus +extern "C" { +#endif + + +// For Mac OS X < 10.5. +#ifndef NSINTEGER_DEFINED +#define NSINTEGER_DEFINED +#if defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) +typedef long NSInteger; +typedef unsigned long NSUInteger; +#define NSIntegerMin LONG_MIN +#define NSIntegerMax LONG_MAX +#define NSUIntegerMax ULONG_MAX +#else // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) +typedef int NSInteger; +typedef unsigned int NSUInteger; +#define NSIntegerMin INT_MIN +#define NSIntegerMax INT_MAX +#define NSUIntegerMax UINT_MAX +#endif // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) +#endif // NSINTEGER_DEFINED + + +#ifndef _JSONKIT_H_ +#define _JSONKIT_H_ + +#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__APPLE_CC__) && (__APPLE_CC__ >= 5465) +#define JK_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) +#else +#define JK_DEPRECATED_ATTRIBUTE +#endif + +#define JSONKIT_VERSION_MAJOR 1 +#define JSONKIT_VERSION_MINOR 4 + +typedef NSUInteger JKFlags; + +/* + JKParseOptionComments : Allow C style // and /_* ... *_/ (without a _, obviously) comments in JSON. + JKParseOptionUnicodeNewlines : Allow Unicode recommended (?:\r\n|[\n\v\f\r\x85\p{Zl}\p{Zp}]) newlines. + JKParseOptionLooseUnicode : Normally the decoder will stop with an error at any malformed Unicode. + This option allows JSON with malformed Unicode to be parsed without reporting an error. + Any malformed Unicode is replaced with \uFFFD, or "REPLACEMENT CHARACTER". + */ + +enum { + JKParseOptionNone = 0, + JKParseOptionStrict = 0, + JKParseOptionComments = (1 << 0), + JKParseOptionUnicodeNewlines = (1 << 1), + JKParseOptionLooseUnicode = (1 << 2), + JKParseOptionPermitTextAfterValidJSON = (1 << 3), + JKParseOptionValidFlags = (JKParseOptionComments | JKParseOptionUnicodeNewlines | JKParseOptionLooseUnicode | JKParseOptionPermitTextAfterValidJSON), +}; +typedef JKFlags JKParseOptionFlags; + +enum { + JKSerializeOptionNone = 0, + JKSerializeOptionPretty = (1 << 0), + JKSerializeOptionEscapeUnicode = (1 << 1), + JKSerializeOptionEscapeForwardSlashes = (1 << 4), + JKSerializeOptionValidFlags = (JKSerializeOptionPretty | JKSerializeOptionEscapeUnicode | JKSerializeOptionEscapeForwardSlashes), +}; +typedef JKFlags JKSerializeOptionFlags; + +#ifdef __OBJC__ + +typedef struct JKParseState JKParseState; // Opaque internal, private type. + +// As a general rule of thumb, if you use a method that doesn't accept a JKParseOptionFlags argument, it defaults to JKParseOptionStrict + +@interface JSONDecoder : NSObject { + JKParseState *parseState; +} ++ (id)decoder; ++ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (void)clearCache; + +// The parse... methods were deprecated in v1.4 in favor of the v1.4 objectWith... methods. +- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead. +- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead. +// The NSData MUST be UTF8 encoded JSON. +- (id)parseJSONData:(NSData *)jsonData JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData: instead. +- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData:error: instead. + +// Methods that return immutable collection objects. +- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length; +- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error; +// The NSData MUST be UTF8 encoded JSON. +- (id)objectWithData:(NSData *)jsonData; +- (id)objectWithData:(NSData *)jsonData error:(NSError **)error; + +// Methods that return mutable collection objects. +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length; +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error; +// The NSData MUST be UTF8 encoded JSON. +- (id)mutableObjectWithData:(NSData *)jsonData; +- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error; + +@end + +//////////// +#pragma mark Deserializing methods +//////////// + +@interface NSString (JSONKitDeserializing) +- (id)objectFromJSONString; +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +- (id)mutableObjectFromJSONString; +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +@end + +@interface NSData (JSONKitDeserializing) +// The NSData MUST be UTF8 encoded JSON. +- (id)objectFromJSONData; +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +- (id)mutableObjectFromJSONData; +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +@end + +//////////// +#pragma mark Serializing methods +//////////// + +@interface NSString (JSONKitSerializing) +// Convenience methods for those that need to serialize the receiving NSString (i.e., instead of having to serialize a NSArray with a single NSString, you can "serialize to JSON" just the NSString). +// Normally, a string that is serialized to JSON has quotation marks surrounding it, which you may or may not want when serializing a single string, and can be controlled with includeQuotes: +// includeQuotes:YES `a "test"...` -> `"a \"test\"..."` +// includeQuotes:NO `a "test"...` -> `a \"test\"...` +- (NSData *)JSONData; // Invokes JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error; +- (NSString *)JSONString; // Invokes JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error; +@end + +@interface NSArray (JSONKitSerializing) +- (NSData *)JSONData; +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +- (NSString *)JSONString; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +@end + +@interface NSDictionary (JSONKitSerializing) +- (NSData *)JSONData; +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +- (NSString *)JSONString; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +@end + +#ifdef __BLOCKS__ + +@interface NSArray (JSONKitSerializingBlockAdditions) +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; +@end + +@interface NSDictionary (JSONKitSerializingBlockAdditions) +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; +@end + +#endif + + +#endif // __OBJC__ + +#endif // _JSONKIT_H_ + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/MP42/JSONKit.m b/MP42/JSONKit.m new file mode 100755 index 0000000..574a74c --- /dev/null +++ b/MP42/JSONKit.m @@ -0,0 +1,3065 @@ +// +// JSONKit.m +// http://github.com/johnezang/JSONKit +// Dual licensed under either the terms of the BSD License, or alternatively +// under the terms of the Apache License, Version 2.0, as specified below. +// + +/* + Copyright (c) 2011, John Engelhart + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the Zang Industries nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/* + Copyright 2011 John Engelhart + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + + +/* + Acknowledgments: + + The bulk of the UTF8 / UTF32 conversion and verification comes + from ConvertUTF.[hc]. It has been modified from the original sources. + + The original sources were obtained from http://www.unicode.org/. + However, the web site no longer seems to host the files. Instead, + the Unicode FAQ http://www.unicode.org/faq//utf_bom.html#gen4 + points to International Components for Unicode (ICU) + http://site.icu-project.org/ as an example of how to write a UTF + converter. + + The decision to use the ConvertUTF.[ch] code was made to leverage + "proven" code. Hopefully the local modifications are bug free. + + The code in isValidCodePoint() is derived from the ICU code in + utf.h for the macros U_IS_UNICODE_NONCHAR and U_IS_UNICODE_CHAR. + + From the original ConvertUTF.[ch]: + + * Copyright 2001-2004 Unicode, Inc. + * + * Disclaimer + * + * This source code is provided as is by Unicode, Inc. No claims are + * made as to fitness for any particular purpose. No warranties of any + * kind are expressed or implied. The recipient agrees to determine + * applicability of information provided. If this file has been + * purchased on magnetic or optical media from Unicode, Inc., the + * sole remedy for any claim will be exchange of defective media + * within 90 days of receipt. + * + * Limitations on Rights to Redistribute This Code + * + * Unicode, Inc. hereby grants the right to freely use the information + * supplied in this file in the creation of products supporting the + * Unicode Standard, and to make copies of this file in any form + * for internal or external distribution as long as this notice + * remains attached. + +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#import "JSONKit.h" + +//#include +#include +#include +#include +#include + +//#import +#import +#import +#import +#import +#import +#import +#import + +#ifndef __has_feature +#define __has_feature(x) 0 +#endif + +#ifdef JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS +#warning As of JSONKit v1.4, JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS is no longer required. It is no longer a valid option. +#endif + +#ifdef __OBJC_GC__ +#error JSONKit does not support Objective-C Garbage Collection +#endif + +#if __has_feature(objc_arc) +#error JSONKit does not support Objective-C Automatic Reference Counting (ARC) +#endif + +// The following checks are really nothing more than sanity checks. +// JSONKit technically has a few problems from a "strictly C99 conforming" standpoint, though they are of the pedantic nitpicking variety. +// In practice, though, for the compilers and architectures we can reasonably expect this code to be compiled for, these pedantic nitpicks aren't really a problem. +// Since we're limited as to what we can do with pre-processor #if checks, these checks are not nearly as through as they should be. + +#if (UINT_MAX != 0xffffffffU) || (INT_MIN != (-0x7fffffff-1)) || (ULLONG_MAX != 0xffffffffffffffffULL) || (LLONG_MIN != (-0x7fffffffffffffffLL-1LL)) +#error JSONKit requires the C 'int' and 'long long' types to be 32 and 64 bits respectively. +#endif + +#if !defined(__LP64__) && ((UINT_MAX != ULONG_MAX) || (INT_MAX != LONG_MAX) || (INT_MIN != LONG_MIN) || (WORD_BIT != LONG_BIT)) +#error JSONKit requires the C 'int' and 'long' types to be the same on 32-bit architectures. +#endif + +// Cocoa / Foundation uses NS*Integer as the type for a lot of arguments. We make sure that NS*Integer is something we are expecting and is reasonably compatible with size_t / ssize_t + +#if (NSUIntegerMax != ULONG_MAX) || (NSIntegerMax != LONG_MAX) || (NSIntegerMin != LONG_MIN) +#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'long' type. +#endif + +#if (NSUIntegerMax != SIZE_MAX) || (NSIntegerMax != SSIZE_MAX) +#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'size_t' type. +#endif + + +// For DJB hash. +#define JK_HASH_INIT (1402737925UL) + +// Use __builtin_clz() instead of trailingBytesForUTF8[] table lookup. +#define JK_FAST_TRAILING_BYTES + +// JK_CACHE_SLOTS must be a power of 2. Default size is 1024 slots. +#define JK_CACHE_SLOTS_BITS (10) +#define JK_CACHE_SLOTS (1UL << JK_CACHE_SLOTS_BITS) +// JK_CACHE_PROBES is the number of probe attempts. +#define JK_CACHE_PROBES (4UL) +// JK_INIT_CACHE_AGE must be < (1 << AGE) - 1, where AGE is sizeof(typeof(AGE)) * 8. +#define JK_INIT_CACHE_AGE (0) + +// JK_TOKENBUFFER_SIZE is the default stack size for the temporary buffer used to hold "non-simple" strings (i.e., contains \ escapes) +#define JK_TOKENBUFFER_SIZE (1024UL * 2UL) + +// JK_STACK_OBJS is the default number of spaces reserved on the stack for temporarily storing pointers to Obj-C objects before they can be transferred to a NSArray / NSDictionary. +#define JK_STACK_OBJS (1024UL * 1UL) + +#define JK_JSONBUFFER_SIZE (1024UL * 4UL) +#define JK_UTF8BUFFER_SIZE (1024UL * 16UL) + +#define JK_ENCODE_CACHE_SLOTS (1024UL) + + +#if defined (__GNUC__) && (__GNUC__ >= 4) +#define JK_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__)) +#define JK_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect)) +#define JK_EXPECT_T(cond) JK_EXPECTED(cond, 1U) +#define JK_EXPECT_F(cond) JK_EXPECTED(cond, 0U) +#define JK_PREFETCH(ptr) __builtin_prefetch(ptr) +#else // defined (__GNUC__) && (__GNUC__ >= 4) +#define JK_ATTRIBUTES(attr, ...) +#define JK_EXPECTED(cond, expect) (cond) +#define JK_EXPECT_T(cond) (cond) +#define JK_EXPECT_F(cond) (cond) +#define JK_PREFETCH(ptr) +#endif // defined (__GNUC__) && (__GNUC__ >= 4) + +#define JK_STATIC_INLINE static __inline__ JK_ATTRIBUTES(always_inline) +#define JK_ALIGNED(arg) JK_ATTRIBUTES(aligned(arg)) +#define JK_UNUSED_ARG JK_ATTRIBUTES(unused) +#define JK_WARN_UNUSED JK_ATTRIBUTES(warn_unused_result) +#define JK_WARN_UNUSED_CONST JK_ATTRIBUTES(warn_unused_result, const) +#define JK_WARN_UNUSED_PURE JK_ATTRIBUTES(warn_unused_result, pure) +#define JK_WARN_UNUSED_SENTINEL JK_ATTRIBUTES(warn_unused_result, sentinel) +#define JK_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(nonnull(arg, ##__VA_ARGS__)) +#define JK_WARN_UNUSED_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(arg, ##__VA_ARGS__)) +#define JK_WARN_UNUSED_CONST_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, const, nonnull(arg, ##__VA_ARGS__)) +#define JK_WARN_UNUSED_PURE_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, pure, nonnull(arg, ##__VA_ARGS__)) + +#if defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) +#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__), alloc_size(as)) +#else // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) +#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__)) +#endif // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) + + +@class JKArray, JKDictionaryEnumerator, JKDictionary; + +enum { + JSONNumberStateStart = 0, + JSONNumberStateFinished = 1, + JSONNumberStateError = 2, + JSONNumberStateWholeNumberStart = 3, + JSONNumberStateWholeNumberMinus = 4, + JSONNumberStateWholeNumberZero = 5, + JSONNumberStateWholeNumber = 6, + JSONNumberStatePeriod = 7, + JSONNumberStateFractionalNumberStart = 8, + JSONNumberStateFractionalNumber = 9, + JSONNumberStateExponentStart = 10, + JSONNumberStateExponentPlusMinus = 11, + JSONNumberStateExponent = 12, +}; + +enum { + JSONStringStateStart = 0, + JSONStringStateParsing = 1, + JSONStringStateFinished = 2, + JSONStringStateError = 3, + JSONStringStateEscape = 4, + JSONStringStateEscapedUnicode1 = 5, + JSONStringStateEscapedUnicode2 = 6, + JSONStringStateEscapedUnicode3 = 7, + JSONStringStateEscapedUnicode4 = 8, + JSONStringStateEscapedUnicodeSurrogate1 = 9, + JSONStringStateEscapedUnicodeSurrogate2 = 10, + JSONStringStateEscapedUnicodeSurrogate3 = 11, + JSONStringStateEscapedUnicodeSurrogate4 = 12, + JSONStringStateEscapedNeedEscapeForSurrogate = 13, + JSONStringStateEscapedNeedEscapedUForSurrogate = 14, +}; + +enum { + JKParseAcceptValue = (1 << 0), + JKParseAcceptComma = (1 << 1), + JKParseAcceptEnd = (1 << 2), + JKParseAcceptValueOrEnd = (JKParseAcceptValue | JKParseAcceptEnd), + JKParseAcceptCommaOrEnd = (JKParseAcceptComma | JKParseAcceptEnd), +}; + +enum { + JKClassUnknown = 0, + JKClassString = 1, + JKClassNumber = 2, + JKClassArray = 3, + JKClassDictionary = 4, + JKClassNull = 5, +}; + +enum { + JKManagedBufferOnStack = 1, + JKManagedBufferOnHeap = 2, + JKManagedBufferLocationMask = (0x3), + JKManagedBufferLocationShift = (0), + + JKManagedBufferMustFree = (1 << 2), +}; +typedef JKFlags JKManagedBufferFlags; + +enum { + JKObjectStackOnStack = 1, + JKObjectStackOnHeap = 2, + JKObjectStackLocationMask = (0x3), + JKObjectStackLocationShift = (0), + + JKObjectStackMustFree = (1 << 2), +}; +typedef JKFlags JKObjectStackFlags; + +enum { + JKTokenTypeInvalid = 0, + JKTokenTypeNumber = 1, + JKTokenTypeString = 2, + JKTokenTypeObjectBegin = 3, + JKTokenTypeObjectEnd = 4, + JKTokenTypeArrayBegin = 5, + JKTokenTypeArrayEnd = 6, + JKTokenTypeSeparator = 7, + JKTokenTypeComma = 8, + JKTokenTypeTrue = 9, + JKTokenTypeFalse = 10, + JKTokenTypeNull = 11, + JKTokenTypeWhiteSpace = 12, +}; +typedef NSUInteger JKTokenType; + +// These are prime numbers to assist with hash slot probing. +enum { + JKValueTypeNone = 0, + JKValueTypeString = 5, + JKValueTypeLongLong = 7, + JKValueTypeUnsignedLongLong = 11, + JKValueTypeDouble = 13, +}; +typedef NSUInteger JKValueType; + +enum { + JKEncodeOptionAsData = 1, + JKEncodeOptionAsString = 2, + JKEncodeOptionAsTypeMask = 0x7, + JKEncodeOptionCollectionObj = (1 << 3), + JKEncodeOptionStringObj = (1 << 4), + JKEncodeOptionStringObjTrimQuotes = (1 << 5), + +}; +typedef NSUInteger JKEncodeOptionType; + +typedef NSUInteger JKHash; + +typedef struct JKTokenCacheItem JKTokenCacheItem; +typedef struct JKTokenCache JKTokenCache; +typedef struct JKTokenValue JKTokenValue; +typedef struct JKParseToken JKParseToken; +typedef struct JKPtrRange JKPtrRange; +typedef struct JKObjectStack JKObjectStack; +typedef struct JKBuffer JKBuffer; +typedef struct JKConstBuffer JKConstBuffer; +typedef struct JKConstPtrRange JKConstPtrRange; +typedef struct JKRange JKRange; +typedef struct JKManagedBuffer JKManagedBuffer; +typedef struct JKFastClassLookup JKFastClassLookup; +typedef struct JKEncodeCache JKEncodeCache; +typedef struct JKEncodeState JKEncodeState; +typedef struct JKObjCImpCache JKObjCImpCache; +typedef struct JKHashTableEntry JKHashTableEntry; + +typedef id (*NSNumberAllocImp)(id receiver, SEL selector); +typedef id (*NSNumberInitWithUnsignedLongLongImp)(id receiver, SEL selector, unsigned long long value); +typedef id (*JKClassFormatterIMP)(id receiver, SEL selector, id object); +#ifdef __BLOCKS__ +typedef id (^JKClassFormatterBlock)(id formatObject); +#endif + + +struct JKPtrRange { + unsigned char *ptr; + size_t length; +}; + +struct JKConstPtrRange { + const unsigned char *ptr; + size_t length; +}; + +struct JKRange { + size_t location, length; +}; + +struct JKManagedBuffer { + JKPtrRange bytes; + JKManagedBufferFlags flags; + size_t roundSizeUpToMultipleOf; +}; + +struct JKObjectStack { + void **objects, **keys; + CFHashCode *cfHashes; + size_t count, index, roundSizeUpToMultipleOf; + JKObjectStackFlags flags; +}; + +struct JKBuffer { + JKPtrRange bytes; +}; + +struct JKConstBuffer { + JKConstPtrRange bytes; +}; + +struct JKTokenValue { + JKConstPtrRange ptrRange; + JKValueType type; + JKHash hash; + union { + long long longLongValue; + unsigned long long unsignedLongLongValue; + double doubleValue; + } number; + JKTokenCacheItem *cacheItem; +}; + +struct JKParseToken { + JKConstPtrRange tokenPtrRange; + JKTokenType type; + JKTokenValue value; + JKManagedBuffer tokenBuffer; +}; + +struct JKTokenCacheItem { + void *object; + JKHash hash; + CFHashCode cfHash; + size_t size; + unsigned char *bytes; + JKValueType type; +}; + +struct JKTokenCache { + JKTokenCacheItem *items; + size_t count; + unsigned int prng_lfsr; + unsigned char age[JK_CACHE_SLOTS]; +}; + +struct JKObjCImpCache { + Class NSNumberClass; + NSNumberAllocImp NSNumberAlloc; + NSNumberInitWithUnsignedLongLongImp NSNumberInitWithUnsignedLongLong; +}; + +struct JKParseState { + JKParseOptionFlags parseOptionFlags; + JKConstBuffer stringBuffer; + size_t atIndex, lineNumber, lineStartIndex; + size_t prev_atIndex, prev_lineNumber, prev_lineStartIndex; + JKParseToken token; + JKObjectStack objectStack; + JKTokenCache cache; + JKObjCImpCache objCImpCache; + NSError *error; + int errorIsPrev; + BOOL mutableCollections; +}; + +struct JKFastClassLookup { + void *stringClass; + void *numberClass; + void *arrayClass; + void *dictionaryClass; + void *nullClass; +}; + +struct JKEncodeCache { + id object; + size_t offset; + size_t length; +}; + +struct JKEncodeState { + JKManagedBuffer utf8ConversionBuffer; + JKManagedBuffer stringBuffer; + size_t atIndex; + JKFastClassLookup fastClassLookup; + JKEncodeCache cache[JK_ENCODE_CACHE_SLOTS]; + JKSerializeOptionFlags serializeOptionFlags; + JKEncodeOptionType encodeOption; + size_t depth; + NSError *error; + id classFormatterDelegate; + SEL classFormatterSelector; + JKClassFormatterIMP classFormatterIMP; +#ifdef __BLOCKS__ + JKClassFormatterBlock classFormatterBlock; +#endif +}; + +// This is a JSONKit private class. +@interface JKSerializer : NSObject { + JKEncodeState *encodeState; +} + +#ifdef __BLOCKS__ +#define JKSERIALIZER_BLOCKS_PROTO id(^)(id object) +#else +#define JKSERIALIZER_BLOCKS_PROTO id +#endif + ++ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +- (void)releaseState; + +@end + +struct JKHashTableEntry { + NSUInteger keyHash; + id key, object; +}; + + +typedef uint32_t UTF32; /* at least 32 bits */ +typedef uint16_t UTF16; /* at least 16 bits */ +typedef uint8_t UTF8; /* typically 8 bits */ + +typedef enum { + conversionOK, /* conversion successful */ + sourceExhausted, /* partial character in source, but hit end */ + targetExhausted, /* insuff. room in target for conversion */ + sourceIllegal /* source sequence is illegal/malformed */ +} ConversionResult; + +#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD +#define UNI_MAX_BMP (UTF32)0x0000FFFF +#define UNI_MAX_UTF16 (UTF32)0x0010FFFF +#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF +#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF +#define UNI_SUR_HIGH_START (UTF32)0xD800 +#define UNI_SUR_HIGH_END (UTF32)0xDBFF +#define UNI_SUR_LOW_START (UTF32)0xDC00 +#define UNI_SUR_LOW_END (UTF32)0xDFFF + + +#if !defined(JK_FAST_TRAILING_BYTES) +static const char trailingBytesForUTF8[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 +}; +#endif + +static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; +static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + +#define JK_AT_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->atIndex])) +#define JK_END_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->stringBuffer.bytes.length])) + + +static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection); +static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex); +static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject); +static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex); + + +static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count); +static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection); +static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary); +static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary); +static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary); +static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry); +static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object); +static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey); + + +static void _JSONDecoderCleanup(JSONDecoder *decoder); + +static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection); + + +static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer); +static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length); +static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize); +static void jk_objectStack_release(JKObjectStack *objectStack); +static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count); +static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount); + +static void jk_error(JKParseState *parseState, NSString *format, ...); +static int jk_parse_string(JKParseState *parseState); +static int jk_parse_number(JKParseState *parseState); +static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr); +JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState); +JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState); +static int jk_parse_next_token(JKParseState *parseState); +static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String); +static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex); +static void *jk_parse_dictionary(JKParseState *parseState); +static void *jk_parse_array(JKParseState *parseState); +static void *jk_object_for_token(JKParseState *parseState); +static void *jk_cachedObjects(JKParseState *parseState); +JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState); +JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy); + + +static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...); +static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...); +static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format); +static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState); +static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format); +static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format); +static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length); +JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr); +JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object); +static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr); + +#define jk_encode_write1(es, dc, f) (JK_EXPECT_F(_jk_encode_prettyPrint) ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f)) + + +JK_STATIC_INLINE size_t jk_min(size_t a, size_t b); +JK_STATIC_INLINE size_t jk_max(size_t a, size_t b); +JK_STATIC_INLINE JKHash jk_calculateHash(JKHash currentHash, unsigned char c); + +// JSONKit v1.4 used both a JKArray : NSArray and JKMutableArray : NSMutableArray, and the same for the dictionary collection type. +// However, Louis Gerbarg (via cocoa-dev) pointed out that Cocoa / Core Foundation actually implements only a single class that inherits from the +// mutable version, and keeps an ivar bit for whether or not that instance is mutable. This means that the immutable versions of the collection +// classes receive the mutating methods, but this is handled by having those methods throw an exception when the ivar bit is set to immutable. +// We adopt the same strategy here. It's both cleaner and gets rid of the method swizzling hackery used in JSONKit v1.4. + + +// This is a workaround for issue #23 https://github.com/johnezang/JSONKit/pull/23 +// Basically, there seem to be a problem with using +load in static libraries on iOS. However, __attribute__ ((constructor)) does work correctly. +// Since we do not require anything "special" that +load provides, and we can accomplish the same thing using __attribute__ ((constructor)), the +load logic was moved here. + +static Class _JKArrayClass = NULL; +static size_t _JKArrayInstanceSize = 0UL; +static Class _JKDictionaryClass = NULL; +static size_t _JKDictionaryInstanceSize = 0UL; + +// For JSONDecoder... +static Class _jk_NSNumberClass = NULL; +static NSNumberAllocImp _jk_NSNumberAllocImp = NULL; +static NSNumberInitWithUnsignedLongLongImp _jk_NSNumberInitWithUnsignedLongLongImp = NULL; + +extern void jk_collectionClassLoadTimeInitialization(void) __attribute__ ((constructor)); + +void jk_collectionClassLoadTimeInitialization(void) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at load time initialization may be less than ideal. + + _JKArrayClass = objc_getClass("JKArray"); + _JKArrayInstanceSize = jk_max(16UL, class_getInstanceSize(_JKArrayClass)); + + _JKDictionaryClass = objc_getClass("JKDictionary"); + _JKDictionaryInstanceSize = jk_max(16UL, class_getInstanceSize(_JKDictionaryClass)); + + // For JSONDecoder... + _jk_NSNumberClass = [NSNumber class]; + _jk_NSNumberAllocImp = (NSNumberAllocImp)[NSNumber methodForSelector:@selector(alloc)]; + + // Hacktacular. Need to do it this way due to the nature of class clusters. + id temp_NSNumber = [NSNumber alloc]; + _jk_NSNumberInitWithUnsignedLongLongImp = (NSNumberInitWithUnsignedLongLongImp)[temp_NSNumber methodForSelector:@selector(initWithUnsignedLongLong:)]; + [[temp_NSNumber init] release]; + temp_NSNumber = NULL; + + [pool release]; pool = NULL; +} + + +#pragma mark - +@interface JKArray : NSMutableArray { + id *objects; + NSUInteger count, capacity, mutations; +} +@end + +@implementation JKArray + ++ (id)allocWithZone:(NSZone *)zone +{ +#pragma unused(zone) + [NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])]; + return(NULL); +} + +static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection) { + NSCParameterAssert((objects != NULL) && (_JKArrayClass != NULL) && (_JKArrayInstanceSize > 0UL)); + JKArray *array = NULL; + if(JK_EXPECT_T((array = (JKArray *)calloc(1UL, _JKArrayInstanceSize)) != NULL)) { // Directly allocate the JKArray instance via calloc. + object_setClass(array, _JKArrayClass); + if((array = [array init]) == NULL) { return(NULL); } + array->capacity = count; + array->count = count; + if(JK_EXPECT_F((array->objects = (id *)malloc(sizeof(id) * array->capacity)) == NULL)) { [array autorelease]; return(NULL); } + memcpy(array->objects, objects, array->capacity * sizeof(id)); + array->mutations = (mutableCollection == NO) ? 0UL : 1UL; + } + return(array); +} + +// Note: The caller is responsible for -retaining the object that is to be added. +static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex) { + NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex <= array->count) && (newObject != NULL)); + if(!((array != NULL) && (array->objects != NULL) && (objectIndex <= array->count) && (newObject != NULL))) { [newObject autorelease]; return; } + if((array->count + 1UL) >= array->capacity) { + id *newObjects = NULL; + if((newObjects = (id *)realloc(array->objects, sizeof(id) * (array->capacity + 16UL))) == NULL) { [NSException raise:NSMallocException format:@"Unable to resize objects array."]; } + array->objects = newObjects; + array->capacity += 16UL; + memset(&array->objects[array->count], 0, sizeof(id) * (array->capacity - array->count)); + } + array->count++; + if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex + 1UL], &array->objects[objectIndex], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[objectIndex] = NULL; } + array->objects[objectIndex] = newObject; +} + +// Note: The caller is responsible for -retaining the object that is to be added. +static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject) { + NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL)); + if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL))) { [newObject autorelease]; return; } + CFRelease(array->objects[objectIndex]); + array->objects[objectIndex] = NULL; + array->objects[objectIndex] = newObject; +} + +static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex) { + NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count > 0UL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL)); + if(!((array != NULL) && (array->objects != NULL) && (array->count > 0UL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL))) { return; } + CFRelease(array->objects[objectIndex]); + array->objects[objectIndex] = NULL; + if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex], &array->objects[objectIndex + 1UL], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[array->count - 1UL] = NULL; } + array->count--; +} + +- (void)dealloc +{ + if(JK_EXPECT_T(objects != NULL)) { + NSUInteger atObject = 0UL; + for(atObject = 0UL; atObject < count; atObject++) { if(JK_EXPECT_T(objects[atObject] != NULL)) { CFRelease(objects[atObject]); objects[atObject] = NULL; } } + free(objects); objects = NULL; + } + + [super dealloc]; +} + +- (NSUInteger)count +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + return(count); +} + +- (void)getObjects:(id *)objectsPtr range:(NSRange)range +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + if((objectsPtr == NULL) && (NSMaxRange(range) > 0UL)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: pointer to objects array is NULL but range length is %lu", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)NSMaxRange(range)]; } + if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)NSMaxRange(range), (unsigned long)count]; } +#ifndef __clang_analyzer__ + memcpy(objectsPtr, objects + range.location, range.length * sizeof(id)); +#endif +} + +- (id)objectAtIndex:(NSUInteger)objectIndex +{ + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } + NSParameterAssert((objects != NULL) && (count <= capacity) && (objects[objectIndex] != NULL)); + return(objects[objectIndex]); +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len +{ + NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (objects != NULL) && (count <= capacity)); + if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; } + if(JK_EXPECT_F(state->state >= count)) { return(0UL); } + + NSUInteger enumeratedCount = 0UL; + while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < count)) { NSParameterAssert(objects[state->state] != NULL); stackbuf[enumeratedCount++] = objects[state->state++]; } + + return(enumeratedCount); +} + +- (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(objectIndex > count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)(count + 1UL)]; } +#ifdef __clang_analyzer__ + [anObject retain]; // Stupid clang analyzer... Issue #19. +#else + anObject = [anObject retain]; +#endif + _JKArrayInsertObjectAtIndex(self, anObject, objectIndex); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (void)removeObjectAtIndex:(NSUInteger)objectIndex +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } + _JKArrayRemoveObjectAtIndex(self, objectIndex); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (void)replaceObjectAtIndex:(NSUInteger)objectIndex withObject:(id)anObject +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } +#ifdef __clang_analyzer__ + [anObject retain]; // Stupid clang analyzer... Issue #19. +#else + anObject = [anObject retain]; +#endif + _JKArrayReplaceObjectAtIndexWithObject(self, objectIndex, anObject); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (id)copyWithZone:(NSZone *)zone +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + return((mutations == 0UL) ? [self retain] : [(NSArray *)[NSArray allocWithZone:zone] initWithObjects:objects count:count]); +} + +- (id)mutableCopyWithZone:(NSZone *)zone +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + return([(NSMutableArray *)[NSMutableArray allocWithZone:zone] initWithObjects:objects count:count]); +} + +@end + + +#pragma mark - +@interface JKDictionaryEnumerator : NSEnumerator { + id collection; + NSUInteger nextObject; +} + +- (id)initWithJKDictionary:(JKDictionary *)initDictionary; +- (NSArray *)allObjects; +- (id)nextObject; + +@end + +@implementation JKDictionaryEnumerator + +- (id)initWithJKDictionary:(JKDictionary *)initDictionary +{ + NSParameterAssert(initDictionary != NULL); + if((self = [super init]) == NULL) { return(NULL); } + if((collection = (id)CFRetain(initDictionary)) == NULL) { [self autorelease]; return(NULL); } + return(self); +} + +- (void)dealloc +{ + if(collection != NULL) { CFRelease(collection); collection = NULL; } + [super dealloc]; +} + +- (NSArray *)allObjects +{ + NSParameterAssert(collection != NULL); + NSUInteger count = [(NSDictionary *)collection count], atObject = 0UL; + id objects[count]; + + while((objects[atObject] = [self nextObject]) != NULL) { NSParameterAssert(atObject < count); atObject++; } + + return([NSArray arrayWithObjects:objects count:atObject]); +} + +- (id)nextObject +{ + NSParameterAssert((collection != NULL) && (_JKDictionaryHashEntry(collection) != NULL)); + JKHashTableEntry *entry = _JKDictionaryHashEntry(collection); + NSUInteger capacity = _JKDictionaryCapacity(collection); + id returnObject = NULL; + + if(entry != NULL) { while((nextObject < capacity) && ((returnObject = entry[nextObject++].key) == NULL)) { /* ... */ } } + + return(returnObject); +} + +@end + +#pragma mark - +@interface JKDictionary : NSMutableDictionary { + NSUInteger count, capacity, mutations; + JKHashTableEntry *entry; +} +@end + +@implementation JKDictionary + ++ (id)allocWithZone:(NSZone *)zone +{ +#pragma unused(zone) + [NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])]; + return(NULL); +} + +// These values are taken from Core Foundation CF-550 CFBasicHash.m. As a bonus, they align very well with our JKHashTableEntry struct too. +static const NSUInteger jk_dictionaryCapacities[] = { + 0UL, 3UL, 7UL, 13UL, 23UL, 41UL, 71UL, 127UL, 191UL, 251UL, 383UL, 631UL, 1087UL, 1723UL, + 2803UL, 4523UL, 7351UL, 11959UL, 19447UL, 31231UL, 50683UL, 81919UL, 132607UL, + 214519UL, 346607UL, 561109UL, 907759UL, 1468927UL, 2376191UL, 3845119UL, + 6221311UL, 10066421UL, 16287743UL, 26354171UL, 42641881UL, 68996069UL, + 111638519UL, 180634607UL, 292272623UL, 472907251UL +}; + +static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count) { + NSUInteger bottom = 0UL, top = sizeof(jk_dictionaryCapacities) / sizeof(NSUInteger), mid = 0UL, tableSize = (NSUInteger)lround(floor(((double)count) * 1.33)); + while(top > bottom) { mid = (top + bottom) / 2UL; if(jk_dictionaryCapacities[mid] < tableSize) { bottom = mid + 1UL; } else { top = mid; } } + return(jk_dictionaryCapacities[bottom]); +} + +static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary) { + NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity)); + + NSUInteger capacityForCount = 0UL; + if(dictionary->capacity < (capacityForCount = _JKDictionaryCapacityForCount(dictionary->count + 1UL))) { // resize + NSUInteger oldCapacity = dictionary->capacity; +#ifndef NS_BLOCK_ASSERTIONS + NSUInteger oldCount = dictionary->count; +#endif + JKHashTableEntry *oldEntry = dictionary->entry; + if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * capacityForCount)) == NULL)) { [NSException raise:NSMallocException format:@"Unable to allocate memory for hash table."]; } + dictionary->capacity = capacityForCount; + dictionary->count = 0UL; + + NSUInteger idx = 0UL; + for(idx = 0UL; idx < oldCapacity; idx++) { if(oldEntry[idx].key != NULL) { _JKDictionaryAddObject(dictionary, oldEntry[idx].keyHash, oldEntry[idx].key, oldEntry[idx].object); oldEntry[idx].keyHash = 0UL; oldEntry[idx].key = NULL; oldEntry[idx].object = NULL; } } + NSCParameterAssert((oldCount == dictionary->count)); + free(oldEntry); oldEntry = NULL; + } +} + +static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection) { + NSCParameterAssert((keys != NULL) && (keyHashes != NULL) && (objects != NULL) && (_JKDictionaryClass != NULL) && (_JKDictionaryInstanceSize > 0UL)); + JKDictionary *dictionary = NULL; + if(JK_EXPECT_T((dictionary = (JKDictionary *)calloc(1UL, _JKDictionaryInstanceSize)) != NULL)) { // Directly allocate the JKDictionary instance via calloc. + object_setClass(dictionary, _JKDictionaryClass); + if((dictionary = [dictionary init]) == NULL) { return(NULL); } + dictionary->capacity = _JKDictionaryCapacityForCount(count); + dictionary->count = 0UL; + + if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * dictionary->capacity)) == NULL)) { [dictionary autorelease]; return(NULL); } + + NSUInteger idx = 0UL; + for(idx = 0UL; idx < count; idx++) { _JKDictionaryAddObject(dictionary, keyHashes[idx], keys[idx], objects[idx]); } + + dictionary->mutations = (mutableCollection == NO) ? 0UL : 1UL; + } + return(dictionary); +} + +- (void)dealloc +{ + if(JK_EXPECT_T(entry != NULL)) { + NSUInteger atEntry = 0UL; + for(atEntry = 0UL; atEntry < capacity; atEntry++) { + if(JK_EXPECT_T(entry[atEntry].key != NULL)) { CFRelease(entry[atEntry].key); entry[atEntry].key = NULL; } + if(JK_EXPECT_T(entry[atEntry].object != NULL)) { CFRelease(entry[atEntry].object); entry[atEntry].object = NULL; } + } + + free(entry); entry = NULL; + } + + [super dealloc]; +} + +static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary) { + NSCParameterAssert(dictionary != NULL); + return(dictionary->entry); +} + +static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary) { + NSCParameterAssert(dictionary != NULL); + return(dictionary->capacity); +} + +static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry) { + NSCParameterAssert((dictionary != NULL) && (entry != NULL) && (entry->key != NULL) && (entry->object != NULL) && (dictionary->count > 0UL) && (dictionary->count <= dictionary->capacity)); + CFRelease(entry->key); entry->key = NULL; + CFRelease(entry->object); entry->object = NULL; + entry->keyHash = 0UL; + dictionary->count--; + // In order for certain invariants that are used to speed up the search for a particular key, we need to "re-add" all the entries in the hash table following this entry until we hit a NULL entry. + NSUInteger removeIdx = entry - dictionary->entry, idx = 0UL; + NSCParameterAssert((removeIdx < dictionary->capacity)); + for(idx = 0UL; idx < dictionary->capacity; idx++) { + NSUInteger entryIdx = (removeIdx + idx + 1UL) % dictionary->capacity; + JKHashTableEntry *atEntry = &dictionary->entry[entryIdx]; + if(atEntry->key == NULL) { break; } + NSUInteger keyHash = atEntry->keyHash; + id key = atEntry->key, object = atEntry->object; + NSCParameterAssert(object != NULL); + atEntry->keyHash = 0UL; + atEntry->key = NULL; + atEntry->object = NULL; + NSUInteger addKeyEntry = keyHash % dictionary->capacity, addIdx = 0UL; + for(addIdx = 0UL; addIdx < dictionary->capacity; addIdx++) { + JKHashTableEntry *atAddEntry = &dictionary->entry[((addKeyEntry + addIdx) % dictionary->capacity)]; + if(JK_EXPECT_T(atAddEntry->key == NULL)) { NSCParameterAssert((atAddEntry->keyHash == 0UL) && (atAddEntry->object == NULL)); atAddEntry->key = key; atAddEntry->object = object; atAddEntry->keyHash = keyHash; break; } + } + } +} + +static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object) { + NSCParameterAssert((dictionary != NULL) && (key != NULL) && (object != NULL) && (dictionary->count < dictionary->capacity) && (dictionary->entry != NULL)); + NSUInteger keyEntry = keyHash % dictionary->capacity, idx = 0UL; + for(idx = 0UL; idx < dictionary->capacity; idx++) { + NSUInteger entryIdx = (keyEntry + idx) % dictionary->capacity; + JKHashTableEntry *atEntry = &dictionary->entry[entryIdx]; + if(JK_EXPECT_F(atEntry->keyHash == keyHash) && JK_EXPECT_T(atEntry->key != NULL) && (JK_EXPECT_F(key == atEntry->key) || JK_EXPECT_F(CFEqual(atEntry->key, key)))) { _JKDictionaryRemoveObjectWithEntry(dictionary, atEntry); } + if(JK_EXPECT_T(atEntry->key == NULL)) { NSCParameterAssert((atEntry->keyHash == 0UL) && (atEntry->object == NULL)); atEntry->key = key; atEntry->object = object; atEntry->keyHash = keyHash; dictionary->count++; return; } + } + + // We should never get here. If we do, we -release the key / object because it's our responsibility. + CFRelease(key); + CFRelease(object); +} + +- (NSUInteger)count +{ + return(count); +} + +static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey) { + NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity)); + if((aKey == NULL) || (dictionary->capacity == 0UL)) { return(NULL); } + NSUInteger keyHash = CFHash(aKey), keyEntry = (keyHash % dictionary->capacity), idx = 0UL; + JKHashTableEntry *atEntry = NULL; + for(idx = 0UL; idx < dictionary->capacity; idx++) { + atEntry = &dictionary->entry[(keyEntry + idx) % dictionary->capacity]; + if(JK_EXPECT_T(atEntry->keyHash == keyHash) && JK_EXPECT_T(atEntry->key != NULL) && ((atEntry->key == aKey) || CFEqual(atEntry->key, aKey))) { NSCParameterAssert(atEntry->object != NULL); return(atEntry); break; } + if(JK_EXPECT_F(atEntry->key == NULL)) { NSCParameterAssert(atEntry->object == NULL); return(NULL); break; } // If the key was in the table, we would have found it by now. + } + return(NULL); +} + +- (id)objectForKey:(id)aKey +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey); + return((entryForKey != NULL) ? entryForKey->object : NULL); +} + +- (void)getObjects:(id *)objects andKeys:(id *)keys +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + NSUInteger atEntry = 0UL; NSUInteger arrayIdx = 0UL; + for(atEntry = 0UL; atEntry < capacity; atEntry++) { + if(JK_EXPECT_T(entry[atEntry].key != NULL)) { + NSCParameterAssert((entry[atEntry].object != NULL) && (arrayIdx < count)); + if(JK_EXPECT_T(keys != NULL)) { keys[arrayIdx] = entry[atEntry].key; } + if(JK_EXPECT_T(objects != NULL)) { objects[arrayIdx] = entry[atEntry].object; } + arrayIdx++; + } + } +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len +{ + NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (entry != NULL) && (count <= capacity)); + if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; } + if(JK_EXPECT_F(state->state >= capacity)) { return(0UL); } + + NSUInteger enumeratedCount = 0UL; + while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < capacity)) { if(JK_EXPECT_T(entry[state->state].key != NULL)) { stackbuf[enumeratedCount++] = entry[state->state].key; } state->state++; } + + return(enumeratedCount); +} + +- (NSEnumerator *)keyEnumerator +{ + return([[[JKDictionaryEnumerator alloc] initWithJKDictionary:self] autorelease]); +} + +- (void)setObject:(id)anObject forKey:(id)aKey +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil value (key: %@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), aKey]; } + + _JKDictionaryResizeIfNeccessary(self); +#ifndef __clang_analyzer__ + aKey = [aKey copy]; // Why on earth would clang complain that this -copy "might leak", + anObject = [anObject retain]; // but this -retain doesn't!? +#endif // __clang_analyzer__ + _JKDictionaryAddObject(self, CFHash(aKey), aKey, anObject); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (void)removeObjectForKey:(id)aKey +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to remove nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey); + if(entryForKey != NULL) { + _JKDictionaryRemoveObjectWithEntry(self, entryForKey); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; + } +} + +- (id)copyWithZone:(NSZone *)zone +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + return((mutations == 0UL) ? [self retain] : [[NSDictionary allocWithZone:zone] initWithDictionary:self]); +} + +- (id)mutableCopyWithZone:(NSZone *)zone +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + return([[NSMutableDictionary allocWithZone:zone] initWithDictionary:self]); +} + +@end + + + +#pragma mark - + +JK_STATIC_INLINE size_t jk_min(size_t a, size_t b) { return((a < b) ? a : b); } +JK_STATIC_INLINE size_t jk_max(size_t a, size_t b) { return((a > b) ? a : b); } + +JK_STATIC_INLINE JKHash jk_calculateHash(JKHash currentHash, unsigned char c) { return((((currentHash << 5) + currentHash) + (c - 29)) ^ (currentHash >> 19)); } + + +static void jk_error(JKParseState *parseState, NSString *format, ...) { + NSCParameterAssert((parseState != NULL) && (format != NULL)); + + va_list varArgsList; + va_start(varArgsList, format); + NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; + va_end(varArgsList); + +#if 0 + const unsigned char *lineStart = parseState->stringBuffer.bytes.ptr + parseState->lineStartIndex; + const unsigned char *lineEnd = lineStart; + const unsigned char *atCharacterPtr = NULL; + + for(atCharacterPtr = lineStart; atCharacterPtr < JK_END_STRING_PTR(parseState); atCharacterPtr++) { lineEnd = atCharacterPtr; if(jk_parse_is_newline(parseState, atCharacterPtr)) { break; } } + + NSString *lineString = @"", *carretString = @""; + if(lineStart < JK_END_STRING_PTR(parseState)) { + lineString = [[[NSString alloc] initWithBytes:lineStart length:(lineEnd - lineStart) encoding:NSUTF8StringEncoding] autorelease]; + carretString = [NSString stringWithFormat:@"%*.*s^", (int)(parseState->atIndex - parseState->lineStartIndex), (int)(parseState->atIndex - parseState->lineStartIndex), " "]; + } +#endif + + if(parseState->error == NULL) { + parseState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + formatString, NSLocalizedDescriptionKey, + [NSNumber numberWithUnsignedLong:parseState->atIndex], @"JKAtIndexKey", + [NSNumber numberWithUnsignedLong:parseState->lineNumber], @"JKLineNumberKey", + //lineString, @"JKErrorLine0Key", + //carretString, @"JKErrorLine1Key", + NULL]]; + } +} + +#pragma mark - +#pragma mark Buffer and Object Stack management functions + +static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer) { + if((managedBuffer->flags & JKManagedBufferMustFree)) { + if(managedBuffer->bytes.ptr != NULL) { free(managedBuffer->bytes.ptr); managedBuffer->bytes.ptr = NULL; } + managedBuffer->flags &= ~JKManagedBufferMustFree; + } + + managedBuffer->bytes.ptr = NULL; + managedBuffer->bytes.length = 0UL; + managedBuffer->flags &= ~JKManagedBufferLocationMask; +} + +static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length) { + jk_managedBuffer_release(managedBuffer); + managedBuffer->bytes.ptr = ptr; + managedBuffer->bytes.length = length; + managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | JKManagedBufferOnStack; +} + +static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize) { + size_t roundedUpNewSize = newSize; + + if(managedBuffer->roundSizeUpToMultipleOf > 0UL) { roundedUpNewSize = newSize + ((managedBuffer->roundSizeUpToMultipleOf - (newSize % managedBuffer->roundSizeUpToMultipleOf)) % managedBuffer->roundSizeUpToMultipleOf); } + + if((roundedUpNewSize != managedBuffer->bytes.length) && (roundedUpNewSize > managedBuffer->bytes.length)) { + if((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnStack) { + NSCParameterAssert((managedBuffer->flags & JKManagedBufferMustFree) == 0); + unsigned char *newBuffer = NULL, *oldBuffer = managedBuffer->bytes.ptr; + + if((newBuffer = (unsigned char *)malloc(roundedUpNewSize)) == NULL) { return(NULL); } + memcpy(newBuffer, oldBuffer, jk_min(managedBuffer->bytes.length, roundedUpNewSize)); + managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | (JKManagedBufferOnHeap | JKManagedBufferMustFree); + managedBuffer->bytes.ptr = newBuffer; + managedBuffer->bytes.length = roundedUpNewSize; + } else { + NSCParameterAssert(((managedBuffer->flags & JKManagedBufferMustFree) != 0) && ((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnHeap)); + if((managedBuffer->bytes.ptr = (unsigned char *)reallocf(managedBuffer->bytes.ptr, roundedUpNewSize)) == NULL) { return(NULL); } + managedBuffer->bytes.length = roundedUpNewSize; + } + } + + return(managedBuffer->bytes.ptr); +} + + + +static void jk_objectStack_release(JKObjectStack *objectStack) { + NSCParameterAssert(objectStack != NULL); + + NSCParameterAssert(objectStack->index <= objectStack->count); + size_t atIndex = 0UL; + for(atIndex = 0UL; atIndex < objectStack->index; atIndex++) { + if(objectStack->objects[atIndex] != NULL) { CFRelease(objectStack->objects[atIndex]); objectStack->objects[atIndex] = NULL; } + if(objectStack->keys[atIndex] != NULL) { CFRelease(objectStack->keys[atIndex]); objectStack->keys[atIndex] = NULL; } + } + objectStack->index = 0UL; + + if(objectStack->flags & JKObjectStackMustFree) { + NSCParameterAssert((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap); + if(objectStack->objects != NULL) { free(objectStack->objects); objectStack->objects = NULL; } + if(objectStack->keys != NULL) { free(objectStack->keys); objectStack->keys = NULL; } + if(objectStack->cfHashes != NULL) { free(objectStack->cfHashes); objectStack->cfHashes = NULL; } + objectStack->flags &= ~JKObjectStackMustFree; + } + + objectStack->objects = NULL; + objectStack->keys = NULL; + objectStack->cfHashes = NULL; + + objectStack->count = 0UL; + objectStack->flags &= ~JKObjectStackLocationMask; +} + +static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count) { + NSCParameterAssert((objectStack != NULL) && (objects != NULL) && (keys != NULL) && (cfHashes != NULL) && (count > 0UL)); + jk_objectStack_release(objectStack); + objectStack->objects = objects; + objectStack->keys = keys; + objectStack->cfHashes = cfHashes; + objectStack->count = count; + objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | JKObjectStackOnStack; +#ifndef NS_BLOCK_ASSERTIONS + size_t idx; + for(idx = 0UL; idx < objectStack->count; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; } +#endif +} + +static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount) { + size_t roundedUpNewCount = newCount; + int returnCode = 0; + + void **newObjects = NULL, **newKeys = NULL; + CFHashCode *newCFHashes = NULL; + + if(objectStack->roundSizeUpToMultipleOf > 0UL) { roundedUpNewCount = newCount + ((objectStack->roundSizeUpToMultipleOf - (newCount % objectStack->roundSizeUpToMultipleOf)) % objectStack->roundSizeUpToMultipleOf); } + + if((roundedUpNewCount != objectStack->count) && (roundedUpNewCount > objectStack->count)) { + if((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnStack) { + NSCParameterAssert((objectStack->flags & JKObjectStackMustFree) == 0); + + if((newObjects = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; } + memcpy(newObjects, objectStack->objects, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *)); + if((newKeys = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; } + memcpy(newKeys, objectStack->keys, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *)); + + if((newCFHashes = (CFHashCode *)calloc(1UL, roundedUpNewCount * sizeof(CFHashCode))) == NULL) { returnCode = 1; goto errorExit; } + memcpy(newCFHashes, objectStack->cfHashes, jk_min(objectStack->count, roundedUpNewCount) * sizeof(CFHashCode)); + + objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | (JKObjectStackOnHeap | JKObjectStackMustFree); + objectStack->objects = newObjects; newObjects = NULL; + objectStack->keys = newKeys; newKeys = NULL; + objectStack->cfHashes = newCFHashes; newCFHashes = NULL; + objectStack->count = roundedUpNewCount; + } else { + NSCParameterAssert(((objectStack->flags & JKObjectStackMustFree) != 0) && ((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap)); + if((newObjects = (void ** )realloc(objectStack->objects, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->objects = newObjects; newObjects = NULL; } else { returnCode = 1; goto errorExit; } + if((newKeys = (void ** )realloc(objectStack->keys, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->keys = newKeys; newKeys = NULL; } else { returnCode = 1; goto errorExit; } + if((newCFHashes = (CFHashCode *)realloc(objectStack->cfHashes, roundedUpNewCount * sizeof(CFHashCode))) != NULL) { objectStack->cfHashes = newCFHashes; newCFHashes = NULL; } else { returnCode = 1; goto errorExit; } + +#ifndef NS_BLOCK_ASSERTIONS + size_t idx; + for(idx = objectStack->count; idx < roundedUpNewCount; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; } +#endif + objectStack->count = roundedUpNewCount; + } + } + + errorExit: + if(newObjects != NULL) { free(newObjects); newObjects = NULL; } + if(newKeys != NULL) { free(newKeys); newKeys = NULL; } + if(newCFHashes != NULL) { free(newCFHashes); newCFHashes = NULL; } + + return(returnCode); +} + +//////////// +#pragma mark - +#pragma mark Unicode related functions + +JK_STATIC_INLINE ConversionResult isValidCodePoint(UTF32 *u32CodePoint) { + ConversionResult result = conversionOK; + UTF32 ch = *u32CodePoint; + + if(JK_EXPECT_F(ch >= UNI_SUR_HIGH_START) && (JK_EXPECT_T(ch <= UNI_SUR_LOW_END))) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } + if(JK_EXPECT_F(ch >= 0xFDD0U) && (JK_EXPECT_F(ch <= 0xFDEFU) || JK_EXPECT_F((ch & 0xFFFEU) == 0xFFFEU)) && JK_EXPECT_T(ch <= 0x10FFFFU)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } + if(JK_EXPECT_F(ch == 0U)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } + + finished: + *u32CodePoint = ch; + return(result); +} + + +static int isLegalUTF8(const UTF8 *source, size_t length) { + const UTF8 *srcptr = source + length; + UTF8 a; + + switch(length) { + default: return(0); // Everything else falls through when "true"... + case 4: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); } + case 3: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); } + case 2: if(JK_EXPECT_F( (a = (*--srcptr)) > 0xBF )) { return(0); } + + switch(*source) { // no fall-through in this inner switch + case 0xE0: if(JK_EXPECT_F(a < 0xA0)) { return(0); } break; + case 0xED: if(JK_EXPECT_F(a > 0x9F)) { return(0); } break; + case 0xF0: if(JK_EXPECT_F(a < 0x90)) { return(0); } break; + case 0xF4: if(JK_EXPECT_F(a > 0x8F)) { return(0); } break; + default: if(JK_EXPECT_F(a < 0x80)) { return(0); } + } + + case 1: if(JK_EXPECT_F((JK_EXPECT_T(*source < 0xC2)) && JK_EXPECT_F(*source >= 0x80))) { return(0); } + } + + if(JK_EXPECT_F(*source > 0xF4)) { return(0); } + + return(1); +} + +static ConversionResult ConvertSingleCodePointInUTF8(const UTF8 *sourceStart, const UTF8 *sourceEnd, UTF8 const **nextUTF8, UTF32 *convertedUTF32) { + ConversionResult result = conversionOK; + const UTF8 *source = sourceStart; + UTF32 ch = 0UL; + +#if !defined(JK_FAST_TRAILING_BYTES) + unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; +#else + unsigned short extraBytesToRead = __builtin_clz(((*source)^0xff) << 25); +#endif + + if(JK_EXPECT_F((source + extraBytesToRead + 1) > sourceEnd) || JK_EXPECT_F(!isLegalUTF8(source, extraBytesToRead + 1))) { + source++; + while((source < sourceEnd) && (((*source) & 0xc0) == 0x80) && ((source - sourceStart) < (extraBytesToRead + 1))) { source++; } + NSCParameterAssert(source <= sourceEnd); + result = ((source < sourceEnd) && (((*source) & 0xc0) != 0x80)) ? sourceIllegal : ((sourceStart + extraBytesToRead + 1) > sourceEnd) ? sourceExhausted : sourceIllegal; + ch = UNI_REPLACEMENT_CHAR; + goto finished; + } + + switch(extraBytesToRead) { // The cases all fall through. + case 5: ch += *source++; ch <<= 6; + case 4: ch += *source++; ch <<= 6; + case 3: ch += *source++; ch <<= 6; + case 2: ch += *source++; ch <<= 6; + case 1: ch += *source++; ch <<= 6; + case 0: ch += *source++; + } + ch -= offsetsFromUTF8[extraBytesToRead]; + + result = isValidCodePoint(&ch); + + finished: + *nextUTF8 = source; + *convertedUTF32 = ch; + + return(result); +} + + +static ConversionResult ConvertUTF32toUTF8 (UTF32 u32CodePoint, UTF8 **targetStart, UTF8 *targetEnd) { + const UTF32 byteMask = 0xBF, byteMark = 0x80; + ConversionResult result = conversionOK; + UTF8 *target = *targetStart; + UTF32 ch = u32CodePoint; + unsigned short bytesToWrite = 0; + + result = isValidCodePoint(&ch); + + // Figure out how many bytes the result will require. Turn any illegally large UTF32 things (> Plane 17) into replacement chars. + if(ch < (UTF32)0x80) { bytesToWrite = 1; } + else if(ch < (UTF32)0x800) { bytesToWrite = 2; } + else if(ch < (UTF32)0x10000) { bytesToWrite = 3; } + else if(ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; } + else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; result = sourceIllegal; } + + target += bytesToWrite; + if (target > targetEnd) { target -= bytesToWrite; result = targetExhausted; goto finished; } + + switch (bytesToWrite) { // note: everything falls through. + case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]); + } + + target += bytesToWrite; + + finished: + *targetStart = target; + return(result); +} + +JK_STATIC_INLINE int jk_string_add_unicodeCodePoint(JKParseState *parseState, uint32_t unicodeCodePoint, size_t *tokenBufferIdx, JKHash *stringHash) { + UTF8 *u8s = &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx]; + ConversionResult result; + + if((result = ConvertUTF32toUTF8(unicodeCodePoint, &u8s, (parseState->token.tokenBuffer.bytes.ptr + parseState->token.tokenBuffer.bytes.length))) != conversionOK) { if(result == targetExhausted) { return(1); } } + size_t utf8len = u8s - &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx], nextIdx = (*tokenBufferIdx) + utf8len; + + while(*tokenBufferIdx < nextIdx) { *stringHash = jk_calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); } + + return(0); +} + +//////////// +#pragma mark - +#pragma mark Decoding / parsing / deserializing functions + +static int jk_parse_string(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *stringStart = JK_AT_STRING_PTR(parseState) + 1; + const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState); + const unsigned char *atStringCharacter = stringStart; + unsigned char *tokenBuffer = parseState->token.tokenBuffer.bytes.ptr; + size_t tokenStartIndex = parseState->atIndex; + size_t tokenBufferIdx = 0UL; + + int onlySimpleString = 1, stringState = JSONStringStateStart; + uint16_t escapedUnicode1 = 0U, escapedUnicode2 = 0U; + uint32_t escapedUnicodeCodePoint = 0U; + JKHash stringHash = JK_HASH_INIT; + + while(1) { + unsigned long currentChar; + + if(JK_EXPECT_F(atStringCharacter == endOfBuffer)) { /* XXX Add error message */ stringState = JSONStringStateError; goto finishedParsing; } + + if(JK_EXPECT_F((currentChar = *atStringCharacter++) >= 0x80UL)) { + const unsigned char *nextValidCharacter = NULL; + UTF32 u32ch = 0U; + ConversionResult result; + + if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter - 1, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { goto switchToSlowPath; } + stringHash = jk_calculateHash(stringHash, currentChar); + while(atStringCharacter < nextValidCharacter) { NSCParameterAssert(JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)); stringHash = jk_calculateHash(stringHash, *atStringCharacter++); } + continue; + } else { + if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; goto finishedParsing; } + + if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { + switchToSlowPath: + onlySimpleString = 0; + stringState = JSONStringStateParsing; + tokenBufferIdx = (atStringCharacter - stringStart) - 1L; + if(JK_EXPECT_F((tokenBufferIdx + 16UL) > parseState->token.tokenBuffer.bytes.length)) { if((tokenBuffer = jk_managedBuffer_resize(&parseState->token.tokenBuffer, tokenBufferIdx + 1024UL)) == NULL) { jk_error(parseState, @"Internal error: Unable to resize temporary buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + memcpy(tokenBuffer, stringStart, tokenBufferIdx); + goto slowMatch; + } + + if(JK_EXPECT_F(currentChar < 0x20UL)) { jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; } + + stringHash = jk_calculateHash(stringHash, currentChar); + } + } + + slowMatch: + + for(atStringCharacter = (stringStart + ((atStringCharacter - stringStart) - 1L)); (atStringCharacter < endOfBuffer) && (tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); atStringCharacter++) { + if((tokenBufferIdx + 16UL) > parseState->token.tokenBuffer.bytes.length) { if((tokenBuffer = jk_managedBuffer_resize(&parseState->token.tokenBuffer, tokenBufferIdx + 1024UL)) == NULL) { jk_error(parseState, @"Internal error: Unable to resize temporary buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + + NSCParameterAssert(tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); + + unsigned long currentChar = (*atStringCharacter), escapedChar; + + if(JK_EXPECT_T(stringState == JSONStringStateParsing)) { + if(JK_EXPECT_T(currentChar >= 0x20UL)) { + if(JK_EXPECT_T(currentChar < (unsigned long)0x80)) { // Not a UTF8 sequence + if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; atStringCharacter++; goto finishedParsing; } + if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { stringState = JSONStringStateEscape; continue; } + stringHash = jk_calculateHash(stringHash, currentChar); + tokenBuffer[tokenBufferIdx++] = currentChar; + continue; + } else { // UTF8 sequence + const unsigned char *nextValidCharacter = NULL; + UTF32 u32ch = 0U; + ConversionResult result; + + if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { + if((result == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal UTF8 sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; } + if(result == sourceExhausted) { jk_error(parseState, @"End of buffer reached while parsing UTF8 in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; } + if(jk_string_add_unicodeCodePoint(parseState, u32ch, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } + atStringCharacter = nextValidCharacter - 1; + continue; + } else { + while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = jk_calculateHash(stringHash, *atStringCharacter++); } + atStringCharacter--; + continue; + } + } + } else { // currentChar < 0x20 + jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; + } + + } else { // stringState != JSONStringStateParsing + int isSurrogate = 1; + + switch(stringState) { + case JSONStringStateEscape: + switch(currentChar) { + case 'u': escapedUnicode1 = 0U; escapedUnicode2 = 0U; escapedUnicodeCodePoint = 0U; stringState = JSONStringStateEscapedUnicode1; break; + + case 'b': escapedChar = '\b'; goto parsedEscapedChar; + case 'f': escapedChar = '\f'; goto parsedEscapedChar; + case 'n': escapedChar = '\n'; goto parsedEscapedChar; + case 'r': escapedChar = '\r'; goto parsedEscapedChar; + case 't': escapedChar = '\t'; goto parsedEscapedChar; + case '\\': escapedChar = '\\'; goto parsedEscapedChar; + case '/': escapedChar = '/'; goto parsedEscapedChar; + case '"': escapedChar = '"'; goto parsedEscapedChar; + + parsedEscapedChar: + stringState = JSONStringStateParsing; + stringHash = jk_calculateHash(stringHash, escapedChar); + tokenBuffer[tokenBufferIdx++] = escapedChar; + break; + + default: jk_error(parseState, @"Invalid escape sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; break; + } + break; + + case JSONStringStateEscapedUnicode1: + case JSONStringStateEscapedUnicode2: + case JSONStringStateEscapedUnicode3: + case JSONStringStateEscapedUnicode4: isSurrogate = 0; + case JSONStringStateEscapedUnicodeSurrogate1: + case JSONStringStateEscapedUnicodeSurrogate2: + case JSONStringStateEscapedUnicodeSurrogate3: + case JSONStringStateEscapedUnicodeSurrogate4: + { + uint16_t hexValue = 0U; + + switch(currentChar) { + case '0' ... '9': hexValue = currentChar - '0'; goto parsedHex; + case 'a' ... 'f': hexValue = (currentChar - 'a') + 10U; goto parsedHex; + case 'A' ... 'F': hexValue = (currentChar - 'A') + 10U; goto parsedHex; + + parsedHex: + if(!isSurrogate) { escapedUnicode1 = (escapedUnicode1 << 4) | hexValue; } else { escapedUnicode2 = (escapedUnicode2 << 4) | hexValue; } + + if(stringState == JSONStringStateEscapedUnicode4) { + if(((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xE000U))) { + if((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xDC00U)) { stringState = JSONStringStateEscapedNeedEscapeForSurrogate; } + else if((escapedUnicode1 >= 0xDC00U) && (escapedUnicode1 < 0xE000U)) { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; } + else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + } + } + else { escapedUnicodeCodePoint = escapedUnicode1; } + } + + if(stringState == JSONStringStateEscapedUnicodeSurrogate4) { + if((escapedUnicode2 < 0xdc00) || (escapedUnicode2 > 0xdfff)) { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; } + else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + } + else { escapedUnicodeCodePoint = ((escapedUnicode1 - 0xd800) * 0x400) + (escapedUnicode2 - 0xdc00) + 0x10000; } + } + + if((stringState == JSONStringStateEscapedUnicode4) || (stringState == JSONStringStateEscapedUnicodeSurrogate4)) { + if((isValidCodePoint(&escapedUnicodeCodePoint) == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + stringState = JSONStringStateParsing; + if(jk_string_add_unicodeCodePoint(parseState, escapedUnicodeCodePoint, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } + } + else if((stringState >= JSONStringStateEscapedUnicode1) && (stringState <= JSONStringStateEscapedUnicodeSurrogate4)) { stringState++; } + break; + + default: jk_error(parseState, @"Unexpected character found in \\u Unicode escape sequence. Found '%c', expected [0-9a-fA-F].", currentChar); stringState = JSONStringStateError; goto finishedParsing; break; + } + } + break; + + case JSONStringStateEscapedNeedEscapeForSurrogate: + if(currentChar == '\\') { stringState = JSONStringStateEscapedNeedEscapedUForSurrogate; } + else { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0) { jk_error(parseState, @"Required a second \\u Unicode escape sequence following a surrogate \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + else { stringState = JSONStringStateParsing; atStringCharacter--; if(jk_string_add_unicodeCodePoint(parseState, UNI_REPLACEMENT_CHAR, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + } + break; + + case JSONStringStateEscapedNeedEscapedUForSurrogate: + if(currentChar == 'u') { stringState = JSONStringStateEscapedUnicodeSurrogate1; } + else { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0) { jk_error(parseState, @"Required a second \\u Unicode escape sequence following a surrogate \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + else { stringState = JSONStringStateParsing; atStringCharacter -= 2; if(jk_string_add_unicodeCodePoint(parseState, UNI_REPLACEMENT_CHAR, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + } + break; + + default: jk_error(parseState, @"Internal error: Unknown stringState. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; break; + } + } + } + +finishedParsing: + + if(JK_EXPECT_T(stringState == JSONStringStateFinished)) { + NSCParameterAssert((parseState->stringBuffer.bytes.ptr + tokenStartIndex) < atStringCharacter); + + parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + tokenStartIndex; + parseState->token.tokenPtrRange.length = (atStringCharacter - parseState->token.tokenPtrRange.ptr); + + if(JK_EXPECT_T(onlySimpleString)) { + NSCParameterAssert(((parseState->token.tokenPtrRange.ptr + 1) < endOfBuffer) && (parseState->token.tokenPtrRange.length >= 2UL) && (((parseState->token.tokenPtrRange.ptr + 1) + (parseState->token.tokenPtrRange.length - 2)) < endOfBuffer)); + parseState->token.value.ptrRange.ptr = parseState->token.tokenPtrRange.ptr + 1; + parseState->token.value.ptrRange.length = parseState->token.tokenPtrRange.length - 2UL; + } else { + parseState->token.value.ptrRange.ptr = parseState->token.tokenBuffer.bytes.ptr; + parseState->token.value.ptrRange.length = tokenBufferIdx; + } + + parseState->token.value.hash = stringHash; + parseState->token.value.type = JKValueTypeString; + parseState->atIndex = (atStringCharacter - parseState->stringBuffer.bytes.ptr); + } + + if(JK_EXPECT_F(stringState != JSONStringStateFinished)) { jk_error(parseState, @"Invalid string."); } + return(JK_EXPECT_T(stringState == JSONStringStateFinished) ? 0 : 1); +} + +static int jk_parse_number(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *numberStart = JK_AT_STRING_PTR(parseState); + const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState); + const unsigned char *atNumberCharacter = NULL; + int numberState = JSONNumberStateWholeNumberStart, isFloatingPoint = 0, isNegative = 0, backup = 0; + size_t startingIndex = parseState->atIndex; + + for(atNumberCharacter = numberStart; (JK_EXPECT_T(atNumberCharacter < endOfBuffer)) && (JK_EXPECT_T(!(JK_EXPECT_F(numberState == JSONNumberStateFinished) || JK_EXPECT_F(numberState == JSONNumberStateError)))); atNumberCharacter++) { + unsigned long currentChar = (unsigned long)(*atNumberCharacter), lowerCaseCC = currentChar | 0x20UL; + + switch(numberState) { + case JSONNumberStateWholeNumberStart: if (currentChar == '-') { numberState = JSONNumberStateWholeNumberMinus; isNegative = 1; break; } + case JSONNumberStateWholeNumberMinus: if (currentChar == '0') { numberState = JSONNumberStateWholeNumberZero; break; } + else if( (currentChar >= '1') && (currentChar <= '9')) { numberState = JSONNumberStateWholeNumber; break; } + else { /* XXX Add error message */ numberState = JSONNumberStateError; break; } + case JSONNumberStateExponentStart: if( (currentChar == '+') || (currentChar == '-')) { numberState = JSONNumberStateExponentPlusMinus; break; } + case JSONNumberStateFractionalNumberStart: + case JSONNumberStateExponentPlusMinus:if(!((currentChar >= '0') && (currentChar <= '9'))) { /* XXX Add error message */ numberState = JSONNumberStateError; break; } + else { if(numberState == JSONNumberStateFractionalNumberStart) { numberState = JSONNumberStateFractionalNumber; } + else { numberState = JSONNumberStateExponent; } break; } + case JSONNumberStateWholeNumberZero: + case JSONNumberStateWholeNumber: if (currentChar == '.') { numberState = JSONNumberStateFractionalNumberStart; isFloatingPoint = 1; break; } + case JSONNumberStateFractionalNumber: if (lowerCaseCC == 'e') { numberState = JSONNumberStateExponentStart; isFloatingPoint = 1; break; } + case JSONNumberStateExponent: if(!((currentChar >= '0') && (currentChar <= '9')) || (numberState == JSONNumberStateWholeNumberZero)) { numberState = JSONNumberStateFinished; backup = 1; break; } + break; + default: /* XXX Add error message */ numberState = JSONNumberStateError; break; + } + } + + parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + startingIndex; + parseState->token.tokenPtrRange.length = (atNumberCharacter - parseState->token.tokenPtrRange.ptr) - backup; + parseState->atIndex = (parseState->token.tokenPtrRange.ptr + parseState->token.tokenPtrRange.length) - parseState->stringBuffer.bytes.ptr; + + if(JK_EXPECT_T(numberState == JSONNumberStateFinished)) { + unsigned char numberTempBuf[parseState->token.tokenPtrRange.length + 4UL]; + unsigned char *endOfNumber = NULL; + + memcpy(numberTempBuf, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length); + numberTempBuf[parseState->token.tokenPtrRange.length] = 0; + + errno = 0; + + // Treat "-0" as a floating point number, which is capable of representing negative zeros. + if(JK_EXPECT_F(parseState->token.tokenPtrRange.length == 2UL) && JK_EXPECT_F(numberTempBuf[1] == '0') && JK_EXPECT_F(isNegative)) { isFloatingPoint = 1; } + + if(isFloatingPoint) { + parseState->token.value.number.doubleValue = strtod((const char *)numberTempBuf, (char **)&endOfNumber); // strtod is documented to return U+2261 (identical to) 0.0 on an underflow error (along with setting errno to ERANGE). + parseState->token.value.type = JKValueTypeDouble; + parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.doubleValue; + parseState->token.value.ptrRange.length = sizeof(double); + parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type); + } else { + if(isNegative) { + parseState->token.value.number.longLongValue = strtoll((const char *)numberTempBuf, (char **)&endOfNumber, 10); + parseState->token.value.type = JKValueTypeLongLong; + parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.longLongValue; + parseState->token.value.ptrRange.length = sizeof(long long); + parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.longLongValue; + } else { + parseState->token.value.number.unsignedLongLongValue = strtoull((const char *)numberTempBuf, (char **)&endOfNumber, 10); + parseState->token.value.type = JKValueTypeUnsignedLongLong; + parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.unsignedLongLongValue; + parseState->token.value.ptrRange.length = sizeof(unsigned long long); + parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.unsignedLongLongValue; + } + } + + if(JK_EXPECT_F(errno != 0)) { + numberState = JSONNumberStateError; + if(errno == ERANGE) { + switch(parseState->token.value.type) { + case JKValueTypeDouble: jk_error(parseState, @"The value '%s' could not be represented as a 'double' due to %s.", numberTempBuf, (parseState->token.value.number.doubleValue == 0.0) ? "underflow" : "overflow"); break; // see above for == 0.0. + case JKValueTypeLongLong: jk_error(parseState, @"The value '%s' exceeded the minimum value that could be represented: %lld.", numberTempBuf, parseState->token.value.number.longLongValue); break; + case JKValueTypeUnsignedLongLong: jk_error(parseState, @"The value '%s' exceeded the maximum value that could be represented: %llu.", numberTempBuf, parseState->token.value.number.unsignedLongLongValue); break; + default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; + } + } + } + if(JK_EXPECT_F(endOfNumber != &numberTempBuf[parseState->token.tokenPtrRange.length]) && JK_EXPECT_F(numberState != JSONNumberStateError)) { numberState = JSONNumberStateError; jk_error(parseState, @"The conversion function did not consume all of the number tokens characters."); } + + size_t hashIndex = 0UL; + for(hashIndex = 0UL; hashIndex < parseState->token.value.ptrRange.length; hashIndex++) { parseState->token.value.hash = jk_calculateHash(parseState->token.value.hash, parseState->token.value.ptrRange.ptr[hashIndex]); } + } + + if(JK_EXPECT_F(numberState != JSONNumberStateFinished)) { jk_error(parseState, @"Invalid number."); } + return(JK_EXPECT_T((numberState == JSONNumberStateFinished)) ? 0 : 1); +} + +JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy) { + parseState->token.tokenPtrRange.ptr = ptr; + parseState->token.tokenPtrRange.length = length; + parseState->token.type = type; + parseState->atIndex += advanceBy; +} + +static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr) { + NSCParameterAssert((parseState != NULL) && (atCharacterPtr != NULL) && (atCharacterPtr >= parseState->stringBuffer.bytes.ptr) && (atCharacterPtr < JK_END_STRING_PTR(parseState))); + const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); + + if(JK_EXPECT_F(atCharacterPtr >= endOfStringPtr)) { return(0UL); } + + if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\n')) { return(1UL); } + if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\r')) { if((JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr)) && ((*(atCharacterPtr + 1)) == '\n')) { return(2UL); } return(1UL); } + if(parseState->parseOptionFlags & JKParseOptionUnicodeNewlines) { + if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xc2)) && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x85))) { return(2UL); } + if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xe2)) && (((atCharacterPtr + 2) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x80) && (((*(atCharacterPtr + 2)) == 0xa8) || ((*(atCharacterPtr + 2)) == 0xa9)))) { return(3UL); } + } + + return(0UL); +} + +JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState) { + size_t newlineAdvanceAtIndex = 0UL; + if(JK_EXPECT_F((newlineAdvanceAtIndex = jk_parse_is_newline(parseState, JK_AT_STRING_PTR(parseState))) > 0UL)) { parseState->lineNumber++; parseState->atIndex += (newlineAdvanceAtIndex - 1UL); parseState->lineStartIndex = parseState->atIndex + 1UL; return(1); } + return(0); +} + +JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState) { +#ifndef __clang_analyzer__ + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *atCharacterPtr = NULL; + const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); + + for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { + if(((*(atCharacterPtr + 0)) == ' ') || ((*(atCharacterPtr + 0)) == '\t')) { continue; } + if(jk_parse_skip_newline(parseState)) { continue; } + if(parseState->parseOptionFlags & JKParseOptionComments) { + if((JK_EXPECT_F((*(atCharacterPtr + 0)) == '/')) && (JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr))) { + if((*(atCharacterPtr + 1)) == '/') { + parseState->atIndex++; + for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { if(jk_parse_skip_newline(parseState)) { break; } } + continue; + } + if((*(atCharacterPtr + 1)) == '*') { + parseState->atIndex++; + for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { + if(jk_parse_skip_newline(parseState)) { continue; } + if(((*(atCharacterPtr + 0)) == '*') && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == '/'))) { parseState->atIndex++; break; } + } + continue; + } + } + } + break; + } +#endif +} + +static int jk_parse_next_token(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *atCharacterPtr = NULL; + const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); + unsigned char currentCharacter = 0U; + int stopParsing = 0; + + parseState->prev_atIndex = parseState->atIndex; + parseState->prev_lineNumber = parseState->lineNumber; + parseState->prev_lineStartIndex = parseState->lineStartIndex; + + jk_parse_skip_whitespace(parseState); + + if((JK_AT_STRING_PTR(parseState) == endOfStringPtr)) { stopParsing = 1; } + + if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr))) { + currentCharacter = *atCharacterPtr; + + if(JK_EXPECT_T(currentCharacter == '"')) { if(JK_EXPECT_T((stopParsing = jk_parse_string(parseState)) == 0)) { jk_set_parsed_token(parseState, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length, JKTokenTypeString, 0UL); } } + else if(JK_EXPECT_T(currentCharacter == ':')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeSeparator, 1UL); } + else if(JK_EXPECT_T(currentCharacter == ',')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeComma, 1UL); } + else if((JK_EXPECT_T(currentCharacter >= '0') && JK_EXPECT_T(currentCharacter <= '9')) || JK_EXPECT_T(currentCharacter == '-')) { if(JK_EXPECT_T((stopParsing = jk_parse_number(parseState)) == 0)) { jk_set_parsed_token(parseState, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length, JKTokenTypeNumber, 0UL); } } + else if(JK_EXPECT_T(currentCharacter == '{')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectBegin, 1UL); } + else if(JK_EXPECT_T(currentCharacter == '}')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectEnd, 1UL); } + else if(JK_EXPECT_T(currentCharacter == '[')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayBegin, 1UL); } + else if(JK_EXPECT_T(currentCharacter == ']')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayEnd, 1UL); } + + else if(JK_EXPECT_T(currentCharacter == 't')) { if(!((JK_EXPECT_T((atCharacterPtr + 4UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'r')) && (JK_EXPECT_T(atCharacterPtr[2] == 'u')) && (JK_EXPECT_T(atCharacterPtr[3] == 'e')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 4UL, JKTokenTypeTrue, 4UL); } } + else if(JK_EXPECT_T(currentCharacter == 'f')) { if(!((JK_EXPECT_T((atCharacterPtr + 5UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'a')) && (JK_EXPECT_T(atCharacterPtr[2] == 'l')) && (JK_EXPECT_T(atCharacterPtr[3] == 's')) && (JK_EXPECT_T(atCharacterPtr[4] == 'e')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 5UL, JKTokenTypeFalse, 5UL); } } + else if(JK_EXPECT_T(currentCharacter == 'n')) { if(!((JK_EXPECT_T((atCharacterPtr + 4UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'u')) && (JK_EXPECT_T(atCharacterPtr[2] == 'l')) && (JK_EXPECT_T(atCharacterPtr[3] == 'l')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 4UL, JKTokenTypeNull, 4UL); } } + else { stopParsing = 1; /* XXX Add error message */ } + } + + if(JK_EXPECT_F(stopParsing)) { jk_error(parseState, @"Unexpected token, wanted '{', '}', '[', ']', ',', ':', 'true', 'false', 'null', '\"STRING\"', 'NUMBER'."); } + return(stopParsing); +} + +static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String) { + NSString *acceptStrings[16]; + int acceptIdx = 0; + if(state & JKParseAcceptValue) { acceptStrings[acceptIdx++] = or1String; } + if(state & JKParseAcceptComma) { acceptStrings[acceptIdx++] = or2String; } + if(state & JKParseAcceptEnd) { acceptStrings[acceptIdx++] = or3String; } + if(acceptIdx == 1) { jk_error(parseState, @"Expected %@, not '%*.*s'", acceptStrings[0], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } + else if(acceptIdx == 2) { jk_error(parseState, @"Expected %@ or %@, not '%*.*s'", acceptStrings[0], acceptStrings[1], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } + else if(acceptIdx == 3) { jk_error(parseState, @"Expected %@, %@, or %@, not '%*.*s", acceptStrings[0], acceptStrings[1], acceptStrings[2], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } +} + +static void *jk_parse_array(JKParseState *parseState) { + size_t startingObjectIndex = parseState->objectStack.index; + int arrayState = JKParseAcceptValueOrEnd, stopParsing = 0; + void *parsedArray = NULL; + + while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) { + if(JK_EXPECT_F(parseState->objectStack.index > (parseState->objectStack.count - 4UL))) { if(jk_objectStack_resize(&parseState->objectStack, parseState->objectStack.count + 128UL)) { jk_error(parseState, @"Internal error: [array] objectsIndex > %zu, resize failed? %@ line %#ld", (parseState->objectStack.count - 4UL), [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } } + + if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) { + void *object = NULL; +#ifndef NS_BLOCK_ASSERTIONS + parseState->objectStack.objects[parseState->objectStack.index] = NULL; + parseState->objectStack.keys [parseState->objectStack.index] = NULL; +#endif + switch(parseState->token.type) { + case JKTokenTypeNumber: + case JKTokenTypeString: + case JKTokenTypeTrue: + case JKTokenTypeFalse: + case JKTokenTypeNull: + case JKTokenTypeArrayBegin: + case JKTokenTypeObjectBegin: + if(JK_EXPECT_F((arrayState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; } + if(JK_EXPECT_F((object = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Object == NULL"); stopParsing = 1; break; } else { parseState->objectStack.objects[parseState->objectStack.index++] = object; arrayState = JKParseAcceptCommaOrEnd; } + break; + case JKTokenTypeArrayEnd: if(JK_EXPECT_T(arrayState & JKParseAcceptEnd)) { NSCParameterAssert(parseState->objectStack.index >= startingObjectIndex); parsedArray = (void *)_JKArrayCreate((id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections); } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ']'."); } stopParsing = 1; break; + case JKTokenTypeComma: if(JK_EXPECT_T(arrayState & JKParseAcceptComma)) { arrayState = JKParseAcceptValue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break; + default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, arrayState, @"a value", @"a comma", @"a ']'"); stopParsing = 1; break; + } + } + } + + if(JK_EXPECT_F(parsedArray == NULL)) { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { if(parseState->objectStack.objects[idx] != NULL) { CFRelease(parseState->objectStack.objects[idx]); parseState->objectStack.objects[idx] = NULL; } } } +#if !defined(NS_BLOCK_ASSERTIONS) + else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } } +#endif + + parseState->objectStack.index = startingObjectIndex; + return(parsedArray); +} + +static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex) { + void *parsedDictionary = NULL; + + parseState->objectStack.index--; + + parsedDictionary = _JKDictionaryCreate((id *)&parseState->objectStack.keys[startingObjectIndex], (NSUInteger *)&parseState->objectStack.cfHashes[startingObjectIndex], (id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections); + + return(parsedDictionary); +} + +static void *jk_parse_dictionary(JKParseState *parseState) { + size_t startingObjectIndex = parseState->objectStack.index; + int dictState = JKParseAcceptValueOrEnd, stopParsing = 0; + void *parsedDictionary = NULL; + + while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) { + if(JK_EXPECT_F(parseState->objectStack.index > (parseState->objectStack.count - 4UL))) { if(jk_objectStack_resize(&parseState->objectStack, parseState->objectStack.count + 128UL)) { jk_error(parseState, @"Internal error: [dictionary] objectsIndex > %zu, resize failed? %@ line #%ld", (parseState->objectStack.count - 4UL), [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } } + + size_t objectStackIndex = parseState->objectStack.index++; + parseState->objectStack.keys[objectStackIndex] = NULL; + parseState->objectStack.objects[objectStackIndex] = NULL; + void *key = NULL, *object = NULL; + + if(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)))) { + switch(parseState->token.type) { + case JKTokenTypeString: + if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected string."); stopParsing = 1; break; } + if(JK_EXPECT_F((key = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Key == NULL."); stopParsing = 1; break; } + else { + parseState->objectStack.keys[objectStackIndex] = key; + if(JK_EXPECT_T(parseState->token.value.cacheItem != NULL)) { if(JK_EXPECT_F(parseState->token.value.cacheItem->cfHash == 0UL)) { parseState->token.value.cacheItem->cfHash = CFHash(key); } parseState->objectStack.cfHashes[objectStackIndex] = parseState->token.value.cacheItem->cfHash; } + else { parseState->objectStack.cfHashes[objectStackIndex] = CFHash(key); } + } + break; + + case JKTokenTypeObjectEnd: if((JK_EXPECT_T(dictState & JKParseAcceptEnd))) { NSCParameterAssert(parseState->objectStack.index >= startingObjectIndex); parsedDictionary = jk_create_dictionary(parseState, startingObjectIndex); } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected '}'."); } stopParsing = 1; break; + case JKTokenTypeComma: if((JK_EXPECT_T(dictState & JKParseAcceptComma))) { dictState = JKParseAcceptValue; parseState->objectStack.index--; continue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break; + + default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a \"STRING\"", @"a comma", @"a '}'"); stopParsing = 1; break; + } + } + + if(JK_EXPECT_T(stopParsing == 0)) { + if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) { if(JK_EXPECT_F(parseState->token.type != JKTokenTypeSeparator)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Expected ':'."); stopParsing = 1; } } + } + + if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) { + switch(parseState->token.type) { + case JKTokenTypeNumber: + case JKTokenTypeString: + case JKTokenTypeTrue: + case JKTokenTypeFalse: + case JKTokenTypeNull: + case JKTokenTypeArrayBegin: + case JKTokenTypeObjectBegin: + if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; } + if(JK_EXPECT_F((object = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Object == NULL."); stopParsing = 1; break; } else { parseState->objectStack.objects[objectStackIndex] = object; dictState = JKParseAcceptCommaOrEnd; } + break; + default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a value", @"a comma", @"a '}'"); stopParsing = 1; break; + } + } + } + + if(JK_EXPECT_F(parsedDictionary == NULL)) { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { if(parseState->objectStack.keys[idx] != NULL) { CFRelease(parseState->objectStack.keys[idx]); parseState->objectStack.keys[idx] = NULL; } if(parseState->objectStack.objects[idx] != NULL) { CFRelease(parseState->objectStack.objects[idx]); parseState->objectStack.objects[idx] = NULL; } } } +#if !defined(NS_BLOCK_ASSERTIONS) + else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } } +#endif + + parseState->objectStack.index = startingObjectIndex; + return(parsedDictionary); +} + +static id json_parse_it(JKParseState *parseState) { + id parsedObject = NULL; + int stopParsing = 0; + + while((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length))) { + if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) { + switch(parseState->token.type) { + case JKTokenTypeArrayBegin: + case JKTokenTypeObjectBegin: parsedObject = [(id)jk_object_for_token(parseState) autorelease]; stopParsing = 1; break; + default: jk_error(parseState, @"Expected either '[' or '{'."); stopParsing = 1; break; + } + } + } + + NSCParameterAssert((parseState->objectStack.index == 0) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + + if((parsedObject == NULL) && (JK_AT_STRING_PTR(parseState) == JK_END_STRING_PTR(parseState))) { jk_error(parseState, @"Reached the end of the buffer."); } + if(parsedObject == NULL) { jk_error(parseState, @"Unable to parse JSON."); } + + if((parsedObject != NULL) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) { + jk_parse_skip_whitespace(parseState); + if((parsedObject != NULL) && ((parseState->parseOptionFlags & JKParseOptionPermitTextAfterValidJSON) == 0) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) { + jk_error(parseState, @"A valid JSON object was parsed but there were additional non-white-space characters remaining."); + parsedObject = NULL; + } + } + + return(parsedObject); +} + +//////////// +#pragma mark - +#pragma mark Object cache + +// This uses a Galois Linear Feedback Shift Register (LFSR) PRNG to pick which item in the cache to age. It has a period of (2^32)-1. +// NOTE: A LFSR *MUST* be initialized to a non-zero value and must always have a non-zero value. The LFSR is initalized to 1 in -initWithParseOptions: +JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (parseState->cache.prng_lfsr != 0U)); + parseState->cache.prng_lfsr = (parseState->cache.prng_lfsr >> 1) ^ ((0U - (parseState->cache.prng_lfsr & 1U)) & 0x80200003U); + parseState->cache.age[parseState->cache.prng_lfsr & (parseState->cache.count - 1UL)] >>= 1; +} + +// The object cache is nothing more than a hash table with open addressing collision resolution that is bounded by JK_CACHE_PROBES attempts. +// +// The hash table is a linear C array of JKTokenCacheItem. The terms "item" and "bucket" are synonymous with the index in to the cache array, i.e. cache.items[bucket]. +// +// Items in the cache have an age associated with them. An items age is incremented using saturating unsigned arithmetic and decremeted using unsigned right shifts. +// Thus, an items age is managed using an AIMD policy- additive increase, multiplicative decrease. All age calculations and manipulations are branchless. +// The primitive C type MUST be unsigned. It is currently a "char", which allows (at a minimum and in practice) 8 bits. +// +// A "useable bucket" is a bucket that is not in use (never populated), or has an age == 0. +// +// When an item is found in the cache, it's age is incremented. +// If a useable bucket hasn't been found, the current item (bucket) is aged along with two random items. +// +// If a value is not found in the cache, and no useable bucket has been found, that value is not added to the cache. + +static void *jk_cachedObjects(JKParseState *parseState) { + unsigned long bucket = parseState->token.value.hash & (parseState->cache.count - 1UL), setBucket = 0UL, useableBucket = 0UL, x = 0UL; + void *parsedAtom = NULL; + + if(JK_EXPECT_F(parseState->token.value.ptrRange.length == 0UL) && JK_EXPECT_T(parseState->token.value.type == JKValueTypeString)) { return(@""); } + + for(x = 0UL; x < JK_CACHE_PROBES; x++) { + if(JK_EXPECT_F(parseState->cache.items[bucket].object == NULL)) { setBucket = 1UL; useableBucket = bucket; break; } + + if((JK_EXPECT_T(parseState->cache.items[bucket].hash == parseState->token.value.hash)) && (JK_EXPECT_T(parseState->cache.items[bucket].size == parseState->token.value.ptrRange.length)) && (JK_EXPECT_T(parseState->cache.items[bucket].type == parseState->token.value.type)) && (JK_EXPECT_T(parseState->cache.items[bucket].bytes != NULL)) && (JK_EXPECT_T(memcmp(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length) == 0U))) { + parseState->cache.age[bucket] = (((uint32_t)parseState->cache.age[bucket]) + 1U) - (((((uint32_t)parseState->cache.age[bucket]) + 1U) >> 31) ^ 1U); + parseState->token.value.cacheItem = &parseState->cache.items[bucket]; + NSCParameterAssert(parseState->cache.items[bucket].object != NULL); + return((void *)CFRetain(parseState->cache.items[bucket].object)); + } else { + if(JK_EXPECT_F(setBucket == 0UL) && JK_EXPECT_F(parseState->cache.age[bucket] == 0U)) { setBucket = 1UL; useableBucket = bucket; } + if(JK_EXPECT_F(setBucket == 0UL)) { parseState->cache.age[bucket] >>= 1; jk_cache_age(parseState); jk_cache_age(parseState); } + // This is the open addressing function. The values length and type are used as a form of "double hashing" to distribute values with the same effective value hash across different object cache buckets. + // The values type is a prime number that is relatively coprime to the other primes in the set of value types and the number of hash table buckets. + bucket = (parseState->token.value.hash + (parseState->token.value.ptrRange.length * (x + 1UL)) + (parseState->token.value.type * (x + 1UL)) + (3UL * (x + 1UL))) & (parseState->cache.count - 1UL); + } + } + + switch(parseState->token.value.type) { + case JKValueTypeString: parsedAtom = (void *)CFStringCreateWithBytes(NULL, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length, kCFStringEncodingUTF8, 0); break; + case JKValueTypeLongLong: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.longLongValue); break; + case JKValueTypeUnsignedLongLong: + if(parseState->token.value.number.unsignedLongLongValue <= LLONG_MAX) { parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.unsignedLongLongValue); } + else { parsedAtom = (void *)parseState->objCImpCache.NSNumberInitWithUnsignedLongLong(parseState->objCImpCache.NSNumberAlloc(parseState->objCImpCache.NSNumberClass, @selector(alloc)), @selector(initWithUnsignedLongLong:), parseState->token.value.number.unsignedLongLongValue); } + break; + case JKValueTypeDouble: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberDoubleType, &parseState->token.value.number.doubleValue); break; + default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; + } + + if(JK_EXPECT_T(setBucket) && (JK_EXPECT_T(parsedAtom != NULL))) { + bucket = useableBucket; + if(JK_EXPECT_T((parseState->cache.items[bucket].object != NULL))) { CFRelease(parseState->cache.items[bucket].object); parseState->cache.items[bucket].object = NULL; } + + if(JK_EXPECT_T((parseState->cache.items[bucket].bytes = (unsigned char *)reallocf(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.length)) != NULL)) { + memcpy(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length); + parseState->cache.items[bucket].object = (void *)CFRetain(parsedAtom); + parseState->cache.items[bucket].hash = parseState->token.value.hash; + parseState->cache.items[bucket].cfHash = 0UL; + parseState->cache.items[bucket].size = parseState->token.value.ptrRange.length; + parseState->cache.items[bucket].type = parseState->token.value.type; + parseState->token.value.cacheItem = &parseState->cache.items[bucket]; + parseState->cache.age[bucket] = JK_INIT_CACHE_AGE; + } else { // The realloc failed, so clear the appropriate fields. + parseState->cache.items[bucket].hash = 0UL; + parseState->cache.items[bucket].cfHash = 0UL; + parseState->cache.items[bucket].size = 0UL; + parseState->cache.items[bucket].type = 0UL; + } + } + + return(parsedAtom); +} + + +static void *jk_object_for_token(JKParseState *parseState) { + void *parsedAtom = NULL; + + parseState->token.value.cacheItem = NULL; + switch(parseState->token.type) { + case JKTokenTypeString: parsedAtom = jk_cachedObjects(parseState); break; + case JKTokenTypeNumber: parsedAtom = jk_cachedObjects(parseState); break; + case JKTokenTypeObjectBegin: parsedAtom = jk_parse_dictionary(parseState); break; + case JKTokenTypeArrayBegin: parsedAtom = jk_parse_array(parseState); break; + case JKTokenTypeTrue: parsedAtom = (void *)kCFBooleanTrue; break; + case JKTokenTypeFalse: parsedAtom = (void *)kCFBooleanFalse; break; + case JKTokenTypeNull: parsedAtom = (void *)kCFNull; break; + default: jk_error(parseState, @"Internal error: Unknown token type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; + } + + return(parsedAtom); +} + +#pragma mark - +@implementation JSONDecoder + ++ (id)decoder +{ + return([self decoderWithParseOptions:JKParseOptionStrict]); +} + ++ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([[[self alloc] initWithParseOptions:parseOptionFlags] autorelease]); +} + +- (id)init +{ + return([self initWithParseOptions:JKParseOptionStrict]); +} + +- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + if((self = [super init]) == NULL) { return(NULL); } + + if(parseOptionFlags & ~JKParseOptionValidFlags) { [self autorelease]; [NSException raise:NSInvalidArgumentException format:@"Invalid parse options."]; } + + if((parseState = (JKParseState *)calloc(1UL, sizeof(JKParseState))) == NULL) { goto errorExit; } + + parseState->parseOptionFlags = parseOptionFlags; + + parseState->token.tokenBuffer.roundSizeUpToMultipleOf = 4096UL; + parseState->objectStack.roundSizeUpToMultipleOf = 2048UL; + + parseState->objCImpCache.NSNumberClass = _jk_NSNumberClass; + parseState->objCImpCache.NSNumberAlloc = _jk_NSNumberAllocImp; + parseState->objCImpCache.NSNumberInitWithUnsignedLongLong = _jk_NSNumberInitWithUnsignedLongLongImp; + + parseState->cache.prng_lfsr = 1U; + parseState->cache.count = JK_CACHE_SLOTS; + if((parseState->cache.items = (JKTokenCacheItem *)calloc(1UL, sizeof(JKTokenCacheItem) * parseState->cache.count)) == NULL) { goto errorExit; } + + return(self); + + errorExit: + if(self) { [self autorelease]; self = NULL; } + return(NULL); +} + +// This is here primarily to support the NSString and NSData convenience functions so the autoreleased JSONDecoder can release most of its resources before the pool pops. +static void _JSONDecoderCleanup(JSONDecoder *decoder) { + if((decoder != NULL) && (decoder->parseState != NULL)) { + jk_managedBuffer_release(&decoder->parseState->token.tokenBuffer); + jk_objectStack_release(&decoder->parseState->objectStack); + + [decoder clearCache]; + if(decoder->parseState->cache.items != NULL) { free(decoder->parseState->cache.items); decoder->parseState->cache.items = NULL; } + + free(decoder->parseState); decoder->parseState = NULL; + } +} + +- (void)dealloc +{ + _JSONDecoderCleanup(self); + [super dealloc]; +} + +- (void)clearCache +{ + if(JK_EXPECT_T(parseState != NULL)) { + if(JK_EXPECT_T(parseState->cache.items != NULL)) { + size_t idx = 0UL; + for(idx = 0UL; idx < parseState->cache.count; idx++) { + if(JK_EXPECT_T(parseState->cache.items[idx].object != NULL)) { CFRelease(parseState->cache.items[idx].object); parseState->cache.items[idx].object = NULL; } + if(JK_EXPECT_T(parseState->cache.items[idx].bytes != NULL)) { free(parseState->cache.items[idx].bytes); parseState->cache.items[idx].bytes = NULL; } + memset(&parseState->cache.items[idx], 0, sizeof(JKTokenCacheItem)); + parseState->cache.age[idx] = 0U; + } + } + } +} + +// This needs to be completely rewritten. +static id _JKParseUTF8String(JKParseState *parseState, BOOL mutableCollections, const unsigned char *string, size_t length, NSError **error) { + NSCParameterAssert((parseState != NULL) && (string != NULL) && (parseState->cache.prng_lfsr != 0U)); + parseState->stringBuffer.bytes.ptr = string; + parseState->stringBuffer.bytes.length = length; + parseState->atIndex = 0UL; + parseState->lineNumber = 1UL; + parseState->lineStartIndex = 0UL; + parseState->prev_atIndex = 0UL; + parseState->prev_lineNumber = 1UL; + parseState->prev_lineStartIndex = 0UL; + parseState->error = NULL; + parseState->errorIsPrev = 0; + parseState->mutableCollections = (mutableCollections == NO) ? NO : YES; + + unsigned char stackTokenBuffer[JK_TOKENBUFFER_SIZE] JK_ALIGNED(64); + jk_managedBuffer_setToStackBuffer(&parseState->token.tokenBuffer, stackTokenBuffer, sizeof(stackTokenBuffer)); + + void *stackObjects [JK_STACK_OBJS] JK_ALIGNED(64); + void *stackKeys [JK_STACK_OBJS] JK_ALIGNED(64); + CFHashCode stackCFHashes[JK_STACK_OBJS] JK_ALIGNED(64); + jk_objectStack_setToStackBuffer(&parseState->objectStack, stackObjects, stackKeys, stackCFHashes, JK_STACK_OBJS); + + id parsedJSON = json_parse_it(parseState); + + if((error != NULL) && (parseState->error != NULL)) { *error = parseState->error; } + + jk_managedBuffer_release(&parseState->token.tokenBuffer); + jk_objectStack_release(&parseState->objectStack); + + parseState->stringBuffer.bytes.ptr = NULL; + parseState->stringBuffer.bytes.length = 0UL; + parseState->atIndex = 0UL; + parseState->lineNumber = 1UL; + parseState->lineStartIndex = 0UL; + parseState->prev_atIndex = 0UL; + parseState->prev_lineNumber = 1UL; + parseState->prev_lineStartIndex = 0UL; + parseState->error = NULL; + parseState->errorIsPrev = 0; + parseState->mutableCollections = NO; + + return(parsedJSON); +} + +//////////// +#pragma mark Deprecated as of v1.4 +//////////// + +// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead. +- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length +{ + return([self objectWithUTF8String:string length:length error:NULL]); +} + +// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead. +- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error +{ + return([self objectWithUTF8String:string length:length error:error]); +} + +// Deprecated in JSONKit v1.4. Use objectWithData: instead. +- (id)parseJSONData:(NSData *)jsonData +{ + return([self objectWithData:jsonData error:NULL]); +} + +// Deprecated in JSONKit v1.4. Use objectWithData:error: instead. +- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error +{ + return([self objectWithData:jsonData error:error]); +} + +//////////// +#pragma mark Methods that return immutable collection objects +//////////// + +- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length +{ + return([self objectWithUTF8String:string length:length error:NULL]); +} + +- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error +{ + if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; } + if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; } + + return(_JKParseUTF8String(parseState, NO, string, (size_t)length, error)); +} + +- (id)objectWithData:(NSData *)jsonData +{ + return([self objectWithData:jsonData error:NULL]); +} + +- (id)objectWithData:(NSData *)jsonData error:(NSError **)error +{ + if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; } + return([self objectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]); +} + +//////////// +#pragma mark Methods that return mutable collection objects +//////////// + +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length +{ + return([self mutableObjectWithUTF8String:string length:length error:NULL]); +} + +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error +{ + if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; } + if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; } + + return(_JKParseUTF8String(parseState, YES, string, (size_t)length, error)); +} + +- (id)mutableObjectWithData:(NSData *)jsonData +{ + return([self mutableObjectWithData:jsonData error:NULL]); +} + +- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error +{ + if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; } + return([self mutableObjectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]); +} + +@end + +/* + The NSString and NSData convenience methods need a little bit of explanation. + + Prior to JSONKit v1.4, the NSString -objectFromJSONStringWithParseOptions:error: method looked like + + const unsigned char *utf8String = (const unsigned char *)[self UTF8String]; + if(utf8String == NULL) { return(NULL); } + size_t utf8Length = strlen((const char *)utf8String); + return([[JSONDecoder decoderWithParseOptions:parseOptionFlags] parseUTF8String:utf8String length:utf8Length error:error]); + + This changed with v1.4 to a more complicated method. The reason for this is to keep the amount of memory that is + allocated, but not yet freed because it is dependent on the autorelease pool to pop before it can be reclaimed. + + In the simpler v1.3 code, this included all the bytes used to store the -UTF8String along with the JSONDecoder and all its overhead. + + Now we use an autoreleased CFMutableData that is sized to the UTF8 length of the NSString in question and is used to hold the UTF8 + conversion of said string. + + Once parsed, the CFMutableData has its length set to 0. This should, hopefully, allow the CFMutableData to realloc and/or free + the buffer. + + Another change made was a slight modification to JSONDecoder so that most of the cleanup work that was done in -dealloc was moved + to a private, internal function. These convenience routines keep the pointer to the autoreleased JSONDecoder and calls + _JSONDecoderCleanup() to early release the decoders resources since we already know that particular decoder is not going to be used + again. + + If everything goes smoothly, this will most likely result in perhaps a few hundred bytes that are allocated but waiting for the + autorelease pool to pop. This is compared to the thousands and easily hundreds of thousands of bytes that would have been in + autorelease limbo. It's more complicated for us, but a win for the user. + + Autorelease objects are used in case things don't go smoothly. By having them autoreleased, we effectively guarantee that our + requirement to -release the object is always met, not matter what goes wrong. The downside is having a an object or two in + autorelease limbo, but we've done our best to minimize that impact, so it all balances out. + */ + +@implementation NSString (JSONKitDeserializing) + +static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection) { + id returnObject = NULL; + CFMutableDataRef mutableData = NULL; + JSONDecoder *decoder = NULL; + + CFIndex stringLength = CFStringGetLength((CFStringRef)jsonString); + NSUInteger stringUTF8Length = [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + + if((mutableData = (CFMutableDataRef)[(id)CFDataCreateMutable(NULL, (NSUInteger)stringUTF8Length) autorelease]) != NULL) { + UInt8 *utf8String = CFDataGetMutableBytePtr(mutableData); + CFIndex usedBytes = 0L, convertedCount = 0L; + + convertedCount = CFStringGetBytes((CFStringRef)jsonString, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, utf8String, (NSUInteger)stringUTF8Length, &usedBytes); + if(JK_EXPECT_F(convertedCount != stringLength) || JK_EXPECT_F(usedBytes < 0L)) { if(error != NULL) { *error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:[NSDictionary dictionaryWithObject:@"An error occurred converting the contents of a NSString to UTF8." forKey:NSLocalizedDescriptionKey]]; } goto exitNow; } + + if(mutableCollection == NO) { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; } + else { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; } + } + +exitNow: + if(mutableData != NULL) { CFDataSetLength(mutableData, 0L); } + if(decoder != NULL) { _JSONDecoderCleanup(decoder); } + return(returnObject); +} + +- (id)objectFromJSONString +{ + return([self objectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self objectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, NO)); +} + + +- (id)mutableObjectFromJSONString +{ + return([self mutableObjectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self mutableObjectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, YES)); +} + +@end + +@implementation NSData (JSONKitDeserializing) + +- (id)objectFromJSONData +{ + return([self objectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self objectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + JSONDecoder *decoder = NULL; + id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithData:self error:error]; + if(decoder != NULL) { _JSONDecoderCleanup(decoder); } + return(returnObject); +} + +- (id)mutableObjectFromJSONData +{ + return([self mutableObjectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self mutableObjectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + JSONDecoder *decoder = NULL; + id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithData:self error:error]; + if(decoder != NULL) { _JSONDecoderCleanup(decoder); } + return(returnObject); +} + + +@end + +//////////// +#pragma mark - +#pragma mark Encoding / deserializing functions + +static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...) { + NSCParameterAssert((encodeState != NULL) && (format != NULL)); + + va_list varArgsList; + va_start(varArgsList, format); + NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; + va_end(varArgsList); + + if(encodeState->error == NULL) { + encodeState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + formatString, NSLocalizedDescriptionKey, + NULL]]; + } +} + +JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object) { + NSCParameterAssert(encodeState != NULL); + if(JK_EXPECT_T(cacheSlot != NULL)) { + NSCParameterAssert((object != NULL) && (startingAtIndex <= encodeState->atIndex)); + cacheSlot->object = object; + cacheSlot->offset = startingAtIndex; + cacheSlot->length = (size_t)(encodeState->atIndex - startingAtIndex); + } +} + +static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...) { + va_list varArgsList, varArgsListCopy; + va_start(varArgsList, format); + va_copy(varArgsListCopy, varArgsList); + + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL)); + + ssize_t formattedStringLength = 0L; + int returnValue = 0; + + if(JK_EXPECT_T((formattedStringLength = vsnprintf((char *)&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex], (encodeState->stringBuffer.bytes.length - encodeState->atIndex), format, varArgsList)) >= (ssize_t)(encodeState->stringBuffer.bytes.length - encodeState->atIndex))) { + NSCParameterAssert(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)); + if(JK_EXPECT_F(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (formattedStringLength * 2UL)+ 4096UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); returnValue = 1; goto exitNow; } + if(JK_EXPECT_F((formattedStringLength = vsnprintf((char *)&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex], (encodeState->stringBuffer.bytes.length - encodeState->atIndex), format, varArgsListCopy)) >= (ssize_t)(encodeState->stringBuffer.bytes.length - encodeState->atIndex))) { jk_encode_error(encodeState, @"vsnprintf failed unexpectedly."); returnValue = 1; goto exitNow; } + } + +exitNow: + va_end(varArgsList); + va_end(varArgsListCopy); + if(JK_EXPECT_T(returnValue == 0)) { encodeState->atIndex += formattedStringLength; jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); } + return(returnValue); +} + +static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL)); + if(JK_EXPECT_F(((encodeState->atIndex + strlen(format) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + strlen(format) + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + size_t formatIdx = 0UL; + for(formatIdx = 0UL; format[formatIdx] != 0; formatIdx++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[formatIdx]; } + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); + return(0); +} + +static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState) { + NSCParameterAssert((encodeState != NULL) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL)); + if(JK_EXPECT_F((encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 16UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_T(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 4096UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\n'; + size_t depthWhiteSpace = 0UL; + for(depthWhiteSpace = 0UL; depthWhiteSpace < (encodeState->depth * 2UL); depthWhiteSpace++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; } + return(0); +} + +static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (format != NULL) && ((depthChange >= -1L) && (depthChange <= 1L)) && ((encodeState->depth == 0UL) ? (depthChange >= 0L) : 1) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL)); + if(JK_EXPECT_F((encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 16UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 4096UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + encodeState->depth += depthChange; + if(JK_EXPECT_T(format[0] == ':')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; } + else { + if(JK_EXPECT_F(depthChange == -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; + if(JK_EXPECT_T(depthChange != -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } } + } + NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); + return(0); +} + +static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0UL)); + if(JK_EXPECT_T((encodeState->atIndex + 4UL) < encodeState->stringBuffer.bytes.length)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; } + else { return(jk_encode_write(encodeState, NULL, 0UL, NULL, format)); } + return(0); +} + +static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex)); + if(JK_EXPECT_F((encodeState->stringBuffer.bytes.length - encodeState->atIndex) < (length + 4UL))) { if(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + 4096UL + length) == NULL) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } } + memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, format, length); + encodeState->atIndex += length; + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); + return(0); +} + +JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr) { + return( ( (((JKHash)objectPtr) >> 21) ^ (((JKHash)objectPtr) >> 9) ) + (((JKHash)objectPtr) >> 4) ); +} + +static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (objectPtr != NULL)); + + id object = (id)objectPtr, encodeCacheObject = object; + int isClass = JKClassUnknown; + size_t startingAtIndex = encodeState->atIndex; + + JKHash objectHash = jk_encode_object_hash(objectPtr); + JKEncodeCache *cacheSlot = &encodeState->cache[objectHash % JK_ENCODE_CACHE_SLOTS]; + + if(JK_EXPECT_T(cacheSlot->object == object)) { + NSCParameterAssert((cacheSlot->object != NULL) && + (cacheSlot->offset < encodeState->atIndex) && ((cacheSlot->offset + cacheSlot->length) < encodeState->atIndex) && + (cacheSlot->offset < encodeState->stringBuffer.bytes.length) && ((cacheSlot->offset + cacheSlot->length) < encodeState->stringBuffer.bytes.length) && + ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length))); + if(JK_EXPECT_F(((encodeState->atIndex + cacheSlot->length + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + cacheSlot->length + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + NSCParameterAssert(((encodeState->atIndex + cacheSlot->length) < encodeState->stringBuffer.bytes.length) && + ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->atIndex))); + memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, encodeState->stringBuffer.bytes.ptr + cacheSlot->offset, cacheSlot->length); + encodeState->atIndex += cacheSlot->length; + return(0); + } + + // When we encounter a class that we do not handle, and we have either a delegate or block that the user supplied to format unsupported classes, + // we "re-run" the object check. However, we re-run the object check exactly ONCE. If the user supplies an object that isn't one of the + // supported classes, we fail the second time (i.e., double fault error). + BOOL rerunningAfterClassFormatter = NO; + rerunAfterClassFormatter:; + + // XXX XXX XXX XXX + // + // We need to work around a bug in 10.7, which breaks ABI compatibility with Objective-C going back not just to 10.0, but OpenStep and even NextStep. + // + // It has long been documented that "the very first thing that a pointer to an Objective-C object "points to" is a pointer to that objects class". + // + // This is euphemistically called "tagged pointers". There are a number of highly technical problems with this, most involving long passages from + // the C standard(s). In short, one can make a strong case, couched from the perspective of the C standard(s), that that 10.7 "tagged pointers" are + // fundamentally Wrong and Broken, and should have never been implemented. Assuming those points are glossed over, because the change is very clearly + // breaking ABI compatibility, this should have resulted in a minimum of a "minimum version required" bump in various shared libraries to prevent + // causes code that used to work just fine to suddenly break without warning. + // + // In fact, the C standard says that the hack below is "undefined behavior"- there is no requirement that the 10.7 tagged pointer hack of setting the + // "lower, unused bits" must be preserved when casting the result to an integer type, but this "works" because for most architectures + // `sizeof(long) == sizeof(void *)` and the compiler uses the same representation for both. (note: this is informal, not meant to be + // normative or pedantically correct). + // + // In other words, while this "works" for now, technically the compiler is not obligated to do "what we want", and a later version of the compiler + // is not required in any way to produce the same results or behavior that earlier versions of the compiler did for the statement below. + // + // Fan-fucking-tastic. + // + // Why not just use `object_getClass()`? Because `object->isa` reduces to (typically) a *single* instruction. Calling `object_getClass()` requires + // that the compiler potentially spill registers, establish a function call frame / environment, and finally execute a "jump subroutine" instruction. + // Then, the called subroutine must spend half a dozen instructions in its prolog, however many instructions doing whatever it does, then half a dozen + // instructions in its prolog. One instruction compared to dozens, maybe a hundred instructions. + // + // Yes, that's one to two orders of magnitude difference. Which is compelling in its own right. When going for performance, you're often happy with + // gains in the two to three percent range. + // + // XXX XXX XXX XXX + + + BOOL workAroundMacOSXABIBreakingBug = (JK_EXPECT_F(((NSUInteger)object) & 0x1)) ? YES : NO; + void *objectISA = (JK_EXPECT_F(workAroundMacOSXABIBreakingBug)) ? NULL : *((void **)objectPtr); + if(JK_EXPECT_F(workAroundMacOSXABIBreakingBug)) { goto slowClassLookup; } + + if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.stringClass)) { isClass = JKClassString; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.numberClass)) { isClass = JKClassNumber; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.dictionaryClass)) { isClass = JKClassDictionary; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.arrayClass)) { isClass = JKClassArray; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.nullClass)) { isClass = JKClassNull; } + else { + slowClassLookup: + if(JK_EXPECT_T([object isKindOfClass:[NSString class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.stringClass = objectISA; } isClass = JKClassString; } + else if(JK_EXPECT_T([object isKindOfClass:[NSNumber class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.numberClass = objectISA; } isClass = JKClassNumber; } + else if(JK_EXPECT_T([object isKindOfClass:[NSDictionary class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.dictionaryClass = objectISA; } isClass = JKClassDictionary; } + else if(JK_EXPECT_T([object isKindOfClass:[NSArray class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.arrayClass = objectISA; } isClass = JKClassArray; } + else if(JK_EXPECT_T([object isKindOfClass:[NSNull class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.nullClass = objectISA; } isClass = JKClassNull; } + else { + if((rerunningAfterClassFormatter == NO) && ( +#ifdef __BLOCKS__ + ((encodeState->classFormatterBlock) && ((object = encodeState->classFormatterBlock(object)) != NULL)) || +#endif + ((encodeState->classFormatterIMP) && ((object = encodeState->classFormatterIMP(encodeState->classFormatterDelegate, encodeState->classFormatterSelector, object)) != NULL)) )) { rerunningAfterClassFormatter = YES; goto rerunAfterClassFormatter; } + + if(rerunningAfterClassFormatter == NO) { jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([encodeCacheObject class])); return(1); } + else { jk_encode_error(encodeState, @"Unable to serialize object class %@ that was returned by the unsupported class formatter. Original object class was %@.", (object == NULL) ? @"NULL" : NSStringFromClass([object class]), NSStringFromClass([encodeCacheObject class])); return(1); } + } + } + + // This is here for the benefit of the optimizer. It allows the optimizer to do loop invariant code motion for the JKClassArray + // and JKClassDictionary cases when printing simple, single characters via jk_encode_write(), which is actually a macro: + // #define jk_encode_write1(es, dc, f) (_jk_encode_prettyPrint ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f)) + int _jk_encode_prettyPrint = JK_EXPECT_T((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0) ? 0 : 1; + + switch(isClass) { + case JKClassString: + { + { + const unsigned char *cStringPtr = (const unsigned char *)CFStringGetCStringPtr((CFStringRef)object, kCFStringEncodingMacRoman); + if(cStringPtr != NULL) { + const unsigned char *utf8String = cStringPtr; + size_t utf8Idx = 0UL; + + CFIndex stringLength = CFStringGetLength((CFStringRef)object); + if(JK_EXPECT_F(((encodeState->atIndex + (stringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (stringLength * 2UL) + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + for(utf8Idx = 0UL; utf8String[utf8Idx] != 0U; utf8Idx++) { + NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length); + NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); + if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U)) { encodeState->atIndex = startingAtIndex; goto slowUTF8Path; } + if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) { + switch(utf8String[utf8Idx]) { + case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break; + case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break; + case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break; + case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break; + case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break; + default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break; + } + } else { + if(JK_EXPECT_F(utf8String[utf8Idx] == '\"') || JK_EXPECT_F(utf8String[utf8Idx] == '\\') || (JK_EXPECT_F(encodeState->serializeOptionFlags & JKSerializeOptionEscapeForwardSlashes) && JK_EXPECT_F(utf8String[utf8Idx] == '/'))) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx]; + } + } + NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length); + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject); + return(0); + } + } + + slowUTF8Path: + { + CFIndex stringLength = CFStringGetLength((CFStringRef)object); + CFIndex maxStringUTF8Length = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 32L; + + if(JK_EXPECT_F((size_t)maxStringUTF8Length > encodeState->utf8ConversionBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->utf8ConversionBuffer, maxStringUTF8Length + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + CFIndex usedBytes = 0L, convertedCount = 0L; + convertedCount = CFStringGetBytes((CFStringRef)object, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, encodeState->utf8ConversionBuffer.bytes.ptr, encodeState->utf8ConversionBuffer.bytes.length - 16L, &usedBytes); + if(JK_EXPECT_F(convertedCount != stringLength) || JK_EXPECT_F(usedBytes < 0L)) { jk_encode_error(encodeState, @"An error occurred converting the contents of a NSString to UTF8."); return(1); } + + if(JK_EXPECT_F((encodeState->atIndex + (maxStringUTF8Length * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (maxStringUTF8Length * 2UL) + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + const unsigned char *utf8String = encodeState->utf8ConversionBuffer.bytes.ptr; + + size_t utf8Idx = 0UL; + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + for(utf8Idx = 0UL; utf8Idx < (size_t)usedBytes; utf8Idx++) { + NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length); + NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); + NSCParameterAssert((CFIndex)utf8Idx < usedBytes); + if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) { + switch(utf8String[utf8Idx]) { + case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break; + case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break; + case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break; + case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break; + case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break; + default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break; + } + } else { + if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U) && (encodeState->serializeOptionFlags & JKSerializeOptionEscapeUnicode)) { + const unsigned char *nextValidCharacter = NULL; + UTF32 u32ch = 0U; + ConversionResult result; + + if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(&utf8String[utf8Idx], &utf8String[usedBytes], (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { jk_encode_error(encodeState, @"Error converting UTF8."); return(1); } + else { + utf8Idx = (nextValidCharacter - utf8String) - 1UL; + if(JK_EXPECT_T(u32ch <= 0xffffU)) { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", u32ch))) { return(1); } } + else { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x\\u%4.4x", (0xd7c0U + (u32ch >> 10)), (0xdc00U + (u32ch & 0x3ffU))))) { return(1); } } + } + } else { + if(JK_EXPECT_F(utf8String[utf8Idx] == '\"') || JK_EXPECT_F(utf8String[utf8Idx] == '\\') || (JK_EXPECT_F(encodeState->serializeOptionFlags & JKSerializeOptionEscapeForwardSlashes) && JK_EXPECT_F(utf8String[utf8Idx] == '/'))) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx]; + } + } + } + NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length); + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject); + return(0); + } + } + break; + + case JKClassNumber: + { + if(object == (id)kCFBooleanTrue) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "true", 4UL)); } + else if(object == (id)kCFBooleanFalse) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "false", 5UL)); } + + const char *objCType = [object objCType]; + char anum[256], *aptr = &anum[255]; + int isNegative = 0; + unsigned long long ullv; + long long llv; + + if(JK_EXPECT_F(objCType == NULL) || JK_EXPECT_F(objCType[0] == 0) || JK_EXPECT_F(objCType[1] != 0)) { jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%s'", (objCType == NULL) ? "" : objCType); return(1); } + + switch(objCType[0]) { + case 'c': case 'i': case 's': case 'l': case 'q': + if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &llv))) { + if(llv < 0LL) { ullv = -llv; isNegative = 1; } else { ullv = llv; isNegative = 0; } + goto convertNumber; + } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); } + break; + case 'C': case 'I': case 'S': case 'L': case 'Q': case 'B': + if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &ullv))) { + convertNumber: + if(JK_EXPECT_F(ullv < 10ULL)) { *--aptr = ullv + '0'; } else { while(JK_EXPECT_T(ullv > 0ULL)) { *--aptr = (ullv % 10ULL) + '0'; ullv /= 10ULL; NSCParameterAssert(aptr > anum); } } + if(isNegative) { *--aptr = '-'; } + NSCParameterAssert(aptr > anum); + return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, aptr, &anum[255] - aptr)); + } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); } + break; + case 'f': case 'd': + { + double dv; + if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberDoubleType, &dv))) { + if(JK_EXPECT_F(!isfinite(dv))) { jk_encode_error(encodeState, @"Floating point values must be finite. JSON does not support NaN or Infinity."); return(1); } + return(jk_encode_printf(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "%.17g", dv)); + } else { jk_encode_error(encodeState, @"Unable to get floating point value from number object."); return(1); } + } + break; + default: jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%c' / 0x%2.2x", objCType[0], objCType[0]); return(1); break; + } + } + break; + + case JKClassArray: + { + int printComma = 0; + CFIndex arrayCount = CFArrayGetCount((CFArrayRef)object), idx = 0L; + if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "["))) { return(1); } + if(JK_EXPECT_F(arrayCount > 1020L)) { + for(id arrayObject in object) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, arrayObject))) { return(1); } } + } else { + void *objects[1024]; + CFArrayGetValues((CFArrayRef)object, CFRangeMake(0L, arrayCount), (const void **)objects); + for(idx = 0L; idx < arrayCount; idx++) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); } } + } + return(jk_encode_write1(encodeState, -1L, "]")); + } + break; + + case JKClassDictionary: + { + int printComma = 0; + CFIndex dictionaryCount = CFDictionaryGetCount((CFDictionaryRef)object), idx = 0L; + id enumerateObject = JK_EXPECT_F(_jk_encode_prettyPrint) ? [[object allKeys] sortedArrayUsingSelector:@selector(compare:)] : object; + + if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "{"))) { return(1); } + if(JK_EXPECT_F(_jk_encode_prettyPrint) || JK_EXPECT_F(dictionaryCount > 1020L)) { + for(id keyObject in enumerateObject) { + if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } + printComma = 1; + void *keyObjectISA = *((void **)keyObject); + if(JK_EXPECT_F((keyObjectISA != encodeState->fastClassLookup.stringClass)) && JK_EXPECT_F(([keyObject isKindOfClass:[NSString class]] == NO))) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keyObject))) { return(1); } + if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, (void *)CFDictionaryGetValue((CFDictionaryRef)object, keyObject)))) { return(1); } + } + } else { + void *keys[1024], *objects[1024]; + CFDictionaryGetKeysAndValues((CFDictionaryRef)object, (const void **)keys, (const void **)objects); + for(idx = 0L; idx < dictionaryCount; idx++) { + if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } + printComma = 1; + void *keyObjectISA = *((void **)keys[idx]); + if(JK_EXPECT_F(keyObjectISA != encodeState->fastClassLookup.stringClass) && JK_EXPECT_F([(id)keys[idx] isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keys[idx]))) { return(1); } + if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); } + } + } + return(jk_encode_write1(encodeState, -1L, "}")); + } + break; + + case JKClassNull: return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "null", 4UL)); break; + + default: jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([object class])); return(1); break; + } + + return(0); +} + + +@implementation JKSerializer + ++ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([[[[self alloc] init] autorelease] serializeObject:object options:optionFlags encodeOption:encodeOption block:block delegate:delegate selector:selector error:error]); +} + +- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ +#ifndef __BLOCKS__ +#pragma unused(block) +#endif + NSParameterAssert((object != NULL) && (encodeState == NULL) && ((delegate != NULL) ? (block == NULL) : 1) && ((block != NULL) ? (delegate == NULL) : 1) && + (((encodeOption & JKEncodeOptionCollectionObj) != 0UL) ? (((encodeOption & JKEncodeOptionStringObj) == 0UL) && ((encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) : 1) && + (((encodeOption & JKEncodeOptionStringObj) != 0UL) ? ((encodeOption & JKEncodeOptionCollectionObj) == 0UL) : 1)); + + id returnObject = NULL; + + if(encodeState != NULL) { [self releaseState]; } + if((encodeState = (struct JKEncodeState *)calloc(1UL, sizeof(JKEncodeState))) == NULL) { [NSException raise:NSMallocException format:@"Unable to allocate state structure."]; return(NULL); } + + if((error != NULL) && (*error != NULL)) { *error = NULL; } + + if(delegate != NULL) { + if(selector == NULL) { [NSException raise:NSInvalidArgumentException format:@"The delegate argument is not NULL, but the selector argument is NULL."]; } + if([delegate respondsToSelector:selector] == NO) { [NSException raise:NSInvalidArgumentException format:@"The serializeUnsupportedClassesUsingDelegate: delegate does not respond to the selector argument."]; } + encodeState->classFormatterDelegate = delegate; + encodeState->classFormatterSelector = selector; + encodeState->classFormatterIMP = (JKClassFormatterIMP)[delegate methodForSelector:selector]; + NSCParameterAssert(encodeState->classFormatterIMP != NULL); + } + +#ifdef __BLOCKS__ + encodeState->classFormatterBlock = block; +#endif + encodeState->serializeOptionFlags = optionFlags; + encodeState->encodeOption = encodeOption; + encodeState->stringBuffer.roundSizeUpToMultipleOf = (1024UL * 32UL); + encodeState->utf8ConversionBuffer.roundSizeUpToMultipleOf = 4096UL; + + unsigned char stackJSONBuffer[JK_JSONBUFFER_SIZE] JK_ALIGNED(64); + jk_managedBuffer_setToStackBuffer(&encodeState->stringBuffer, stackJSONBuffer, sizeof(stackJSONBuffer)); + + unsigned char stackUTF8Buffer[JK_UTF8BUFFER_SIZE] JK_ALIGNED(64); + jk_managedBuffer_setToStackBuffer(&encodeState->utf8ConversionBuffer, stackUTF8Buffer, sizeof(stackUTF8Buffer)); + + if(((encodeOption & JKEncodeOptionCollectionObj) != 0UL) && (([object isKindOfClass:[NSArray class]] == NO) && ([object isKindOfClass:[NSDictionary class]] == NO))) { jk_encode_error(encodeState, @"Unable to serialize object class %@, expected a NSArray or NSDictionary.", NSStringFromClass([object class])); goto errorExit; } + if(((encodeOption & JKEncodeOptionStringObj) != 0UL) && ([object isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Unable to serialize object class %@, expected a NSString.", NSStringFromClass([object class])); goto errorExit; } + + if(jk_encode_add_atom_to_buffer(encodeState, object) == 0) { + BOOL stackBuffer = ((encodeState->stringBuffer.flags & JKManagedBufferMustFree) == 0UL) ? YES : NO; + + if((encodeState->atIndex < 2UL)) + if((stackBuffer == NO) && ((encodeState->stringBuffer.bytes.ptr = (unsigned char *)reallocf(encodeState->stringBuffer.bytes.ptr, encodeState->atIndex + 16UL)) == NULL)) { jk_encode_error(encodeState, @"Unable to realloc buffer"); goto errorExit; } + + switch((encodeOption & JKEncodeOptionAsTypeMask)) { + case JKEncodeOptionAsData: + if(stackBuffer == YES) { if((returnObject = [(id)CFDataCreate( NULL, encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSData object"); } } + else { if((returnObject = [(id)CFDataCreateWithBytesNoCopy( NULL, encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, NULL) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSData object"); } } + break; + + case JKEncodeOptionAsString: + if(stackBuffer == YES) { if((returnObject = [(id)CFStringCreateWithBytes( NULL, (const UInt8 *)encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, kCFStringEncodingUTF8, NO) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSString object"); } } + else { if((returnObject = [(id)CFStringCreateWithBytesNoCopy(NULL, (const UInt8 *)encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, kCFStringEncodingUTF8, NO, NULL) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSString object"); } } + break; + + default: jk_encode_error(encodeState, @"Unknown encode as type."); break; + } + + if((returnObject != NULL) && (stackBuffer == NO)) { encodeState->stringBuffer.flags &= ~JKManagedBufferMustFree; encodeState->stringBuffer.bytes.ptr = NULL; encodeState->stringBuffer.bytes.length = 0UL; } + } + +errorExit: + if((encodeState != NULL) && (error != NULL) && (encodeState->error != NULL)) { *error = encodeState->error; encodeState->error = NULL; } + [self releaseState]; + + return(returnObject); +} + +- (void)releaseState +{ + if(encodeState != NULL) { + jk_managedBuffer_release(&encodeState->stringBuffer); + jk_managedBuffer_release(&encodeState->utf8ConversionBuffer); + free(encodeState); encodeState = NULL; + } +} + +- (void)dealloc +{ + [self releaseState]; + [super dealloc]; +} + +@end + +@implementation NSString (JSONKitSerializing) + +//////////// +#pragma mark Methods for serializing a single NSString. +//////////// + +// Useful for those who need to serialize just a NSString. Otherwise you would have to do something like [NSArray arrayWithObject:stringToBeJSONSerialized], serializing the array, and then chopping of the extra ^\[.*\]$ square brackets. + +// NSData returning methods... + +- (NSData *)JSONData +{ + return([self JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +// NSString returning methods... + +- (NSString *)JSONString +{ + return([self JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +@end + +@implementation NSArray (JSONKitSerializing) + +// NSData returning methods... + +- (NSData *)JSONData +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +// NSString returning methods... + +- (NSString *)JSONString +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +@end + +@implementation NSDictionary (JSONKitSerializing) + +// NSData returning methods... + +- (NSData *)JSONData +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +// NSString returning methods... + +- (NSString *)JSONString +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +@end + + +#ifdef __BLOCKS__ + +@implementation NSArray (JSONKitSerializingBlockAdditions) + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +@end + +@implementation NSDictionary (JSONKitSerializingBlockAdditions) + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +@end + +#endif // __BLOCKS__ + diff --git a/MP42/MP42.h b/MP42/MP42.h deleted file mode 100644 index a17a805..0000000 --- a/MP42/MP42.h +++ /dev/null @@ -1,13 +0,0 @@ -// -// MP42.h -// MP42 -// -// Created by Damiano Galassi on 01/11/13. -// Copyright (c) 2013 Damiano Galassi. All rights reserved. -// - -#import - -@interface MP42 : NSObject - -@end diff --git a/MP42/MP42.m b/MP42/MP42.m deleted file mode 100644 index 16d899f..0000000 --- a/MP42/MP42.m +++ /dev/null @@ -1,13 +0,0 @@ -// -// MP42.m -// MP42 -// -// Created by Damiano Galassi on 01/11/13. -// Copyright (c) 2013 Damiano Galassi. All rights reserved. -// - -#import "MP42.h" - -@implementation MP42 - -@end diff --git a/MP42/MP42AACImporter.h b/MP42/MP42AACImporter.h new file mode 100644 index 0000000..d72635d --- /dev/null +++ b/MP42/MP42AACImporter.h @@ -0,0 +1,20 @@ +// +// MP42AACFileImporter.h +// Subler +// +// Created by Damiano Galassi on 07/12/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import +#import "MP42FileImporter.h" + +@interface MP42AACImporter : MP42FileImporter { + FILE* inFile; + int64_t size; + + NSMutableData *aacInfo; + u_int32_t samplesPerSecond; +} + +@end \ No newline at end of file diff --git a/MP42/MP42AACImporter.mm b/MP42/MP42AACImporter.mm new file mode 100644 index 0000000..1691a67 --- /dev/null +++ b/MP42/MP42AACImporter.mm @@ -0,0 +1,883 @@ +// +// MP42AacFileImporter.m +// Subler +// +// Created by Damiano Galassi on 07/12/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import "MP42AACImporter.h" +#import "SBLanguages.h" +#import "MP42File.h" + +@implementation MP42AACImporter + +static int aacUseOldFile = 0; +static int aacProfileLevel = 4; + +#define MP4AV_AAC_MAIN_PROFILE 0 +#define MP4AV_AAC_LC_PROFILE 1 +#define MP4AV_AAC_SSR_PROFILE 2 +#define MP4AV_AAC_LTP_PROFILE 3 + +#include +#include /* isdigit, isprint, isspace */ +#include +#include +#include +#include +#include +#include +#include "mbs.h" +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + + uint8_t MP4AV_AacConfigGetAudioObjectType(uint8_t *pConfig); + + u_int8_t MP4AV_AacConfigGetSamplingRateIndex( + u_int8_t* pConfig); + + u_int32_t MP4AV_AacConfigGetSamplingRate( + u_int8_t* pConfig); + + u_int16_t MP4AV_AacConfigGetSamplingWindow( + u_int8_t* pConfig); + + u_int8_t MP4AV_AacConfigGetChannels( + u_int8_t* pConfig); + + bool MP4AV_AacGetConfigurationFromAdts( + u_int8_t** ppConfig, + u_int32_t* pConfigLength, + u_int8_t* pAdtsHdr); + + bool MP4AV_AacGetConfiguration( + u_int8_t** ppConfig, + u_int32_t* pConfigLength, + u_int8_t profile, + u_int32_t samplingRate, + u_int8_t channels); + + bool MP4AV_AacGetConfiguration_SBR( + u_int8_t** ppConfig, + u_int32_t* pConfigLength, + u_int8_t profile, + u_int32_t samplingRate, + u_int8_t channels); + + void MP4AV_LatmGetConfiguration(uint8_t **ppConfig, + uint32_t *pConfigLength, + const uint8_t *AudioSpecificConfig, + uint32_t AudioSpecificConfigLen); + bool MP4AV_AacGetConfiguration_LATM(u_int8_t** ppConfig, + u_int32_t* pConfigLength, + u_int8_t profile, + u_int32_t samplingRate, + u_int8_t channels); +#ifdef __cplusplus +} +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define NUM_ADTS_SAMPLING_RATES 16 + + extern u_int32_t AdtsSamplingRates[NUM_ADTS_SAMPLING_RATES]; + + bool MP4AV_AdtsGetNextFrame( + u_int8_t* pSrc, + u_int32_t srcLength, + u_int8_t** ppFrame, + u_int32_t* pFrameSize); + + u_int16_t MP4AV_AdtsGetFrameSize( + u_int8_t* pHdr); + + u_int16_t MP4AV_AdtsGetHeaderBitSize( + u_int8_t* pHdr); + + u_int16_t MP4AV_AdtsGetHeaderByteSize( + u_int8_t* pHdr); + + u_int8_t MP4AV_AdtsGetVersion( + u_int8_t* pHdr); + + u_int8_t MP4AV_AdtsGetProfile( + u_int8_t* pHdr); + + u_int8_t MP4AV_AdtsGetSamplingRateIndex( + u_int8_t* pHdr); + + u_int8_t MP4AV_AdtsFindSamplingRateIndex( + u_int32_t samplingRate); + + u_int32_t MP4AV_AdtsGetSamplingRate( + u_int8_t* pHdr); + + u_int8_t MP4AV_AdtsGetChannels( + u_int8_t* pHdr); + + bool MP4AV_AdtsMakeFrame( + u_int8_t* pData, + u_int16_t dataLength, + bool isMpeg2, + u_int8_t profile, + u_int32_t samplingFrequency, + u_int8_t channels, + u_int8_t** ppAdtsData, + u_int32_t* pAdtsDataLength); + + +#ifdef __cplusplus +} +#endif + +/* + * ADTS Header: + * MPEG-2 version 56 bits (byte aligned) + * MPEG-4 version 56 bits (byte aligned) - note - changed for 0.99 version + * + * syncword 12 bits + * id 1 bit + * layer 2 bits + * protection_absent 1 bit + * profile 2 bits + * sampling_frequency_index 4 bits + * private 1 bit + * channel_configuraton 3 bits + * original 1 bit + * home 1 bit + * copyright_id 1 bit + * copyright_id_start 1 bit + * aac_frame_length 13 bits + * adts_buffer_fullness 11 bits + * num_raw_data_blocks 2 bits + * + * if (protection_absent == 0) + * crc_check 16 bits + */ + +#define NUM_ADTS_SAMPLING_RATES 16 + +u_int32_t AdtsSamplingRates[NUM_ADTS_SAMPLING_RATES] = { + 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, + 16000, 12000, 11025, 8000, 7350, 0, 0, 0 +}; + +/* + * compute ADTS frame size + */ +u_int16_t MP4AV_AdtsGetFrameSize(u_int8_t* pHdr) +{ + /* extract the necessary fields from the header */ + uint16_t frameLength; + + frameLength = (((u_int16_t)(pHdr[3] & 0x3)) << 11) + | (((u_int16_t)pHdr[4]) << 3) | (pHdr[5] >> 5); + + return frameLength; +} + +/* + * Compute length of ADTS header in bits + */ +u_int16_t MP4AV_AdtsGetHeaderBitSize(u_int8_t* pHdr) +{ + u_int8_t hasCrc = !(pHdr[1] & 0x01); + u_int16_t hdrSize; + + hdrSize = 56; + + if (hasCrc) { + hdrSize += 16; + } + return hdrSize; +} + +u_int16_t MP4AV_AdtsGetHeaderByteSize(u_int8_t* pHdr) +{ + return (MP4AV_AdtsGetHeaderBitSize(pHdr) + 7) / 8; +} + +u_int8_t MP4AV_AdtsGetVersion(u_int8_t* pHdr) +{ + return (pHdr[1] & 0x08) >> 3; +} + +u_int8_t MP4AV_AdtsGetProfile(u_int8_t* pHdr) +{ + return (pHdr[2] & 0xc0) >> 6; +} + +u_int8_t MP4AV_AdtsGetSamplingRateIndex(u_int8_t* pHdr) +{ + return (pHdr[2] & 0x3c) >> 2; +} + +u_int8_t MP4AV_AdtsFindSamplingRateIndex(u_int32_t samplingRate) +{ + for (u_int8_t i = 0; i < NUM_ADTS_SAMPLING_RATES; i++) { + if (samplingRate == AdtsSamplingRates[i]) { + return i; + } + } + return NUM_ADTS_SAMPLING_RATES - 1; +} + +u_int32_t MP4AV_AdtsGetSamplingRate(u_int8_t* pHdr) +{ + return AdtsSamplingRates[MP4AV_AdtsGetSamplingRateIndex(pHdr)]; +} + +u_int8_t MP4AV_AdtsGetChannels(u_int8_t* pHdr) +{ + return ((pHdr[2] & 0x1) << 2) | ((pHdr[3] & 0xc0) >> 6); +} + + +bool MP4AV_AdtsMakeFrame( + u_int8_t* pData, + u_int16_t dataLength, + bool isMpeg2, + u_int8_t profile, + u_int32_t samplingFrequency, + u_int8_t channels, + u_int8_t** ppAdtsData, + u_int32_t* pAdtsDataLength) +{ + *pAdtsDataLength = 7 + dataLength; // 56 bits only + + CMemoryBitstream adts; + + try { + adts.AllocBytes(*pAdtsDataLength); + *ppAdtsData = adts.GetBuffer(); + + // build adts header + adts.PutBits(0xFFF, 12); // syncword + adts.PutBits(isMpeg2, 1); // id + adts.PutBits(0, 2); // layer + adts.PutBits(1, 1); // protection_absent + adts.PutBits(profile, 2); // profile + adts.PutBits( + MP4AV_AdtsFindSamplingRateIndex(samplingFrequency), + 4); // sampling_frequency_index + adts.PutBits(0, 1); // private + adts.PutBits(channels, 3); // channel_configuration + adts.PutBits(0, 1); // original + adts.PutBits(0, 1); // home + + adts.PutBits(0, 1); // copyright_id + adts.PutBits(0, 1); // copyright_id_start + adts.PutBits(*pAdtsDataLength, 13); // aac_frame_length + adts.PutBits(0x7FF, 11); // adts_buffer_fullness + adts.PutBits(0, 2); // num_raw_data_blocks + + // copy audio frame data + adts.PutBytes(pData, dataLength); + } + catch (...) { + return false; + } + + return true; +} + +/* + * AAC Config in ES: + * + * AudioObjectType 5 bits + * samplingFrequencyIndex 4 bits + * if (samplingFrequencyIndex == 0xF) + * samplingFrequency 24 bits + * channelConfiguration 4 bits + * GA_SpecificConfig + * FrameLengthFlag 1 bit 1024 or 960 + * DependsOnCoreCoder 1 bit (always 0) + * ExtensionFlag 1 bit (always 0) + */ + +extern "C" uint8_t MP4AV_AacConfigGetAudioObjectType (uint8_t *pConfig) +{ + return pConfig[0] >> 3; +} + +extern "C" u_int8_t MP4AV_AacConfigGetSamplingRateIndex(u_int8_t* pConfig) +{ + return ((pConfig[0] << 1) | (pConfig[1] >> 7)) & 0xF; +} + +extern "C" u_int32_t MP4AV_AacConfigGetSamplingRate(u_int8_t* pConfig) +{ + u_int8_t index = + MP4AV_AacConfigGetSamplingRateIndex(pConfig); + + if (index == 0xF) { + return (pConfig[1] & 0x7F) << 17 + | pConfig[2] << 9 + | pConfig[3] << 1 + | (pConfig[4] >> 7); + } + return AdtsSamplingRates[index]; +} + +extern "C" u_int16_t MP4AV_AacConfigGetSamplingWindow(u_int8_t* pConfig) +{ + u_int8_t adjust = 0; + + if (MP4AV_AacConfigGetSamplingRateIndex(pConfig) == 0xF) { + adjust = 3; + } + + if ((pConfig[1 + adjust] >> 2) & 0x1) { + return 960; + } + return 1024; +} + +extern "C" u_int8_t MP4AV_AacConfigGetChannels(u_int8_t* pConfig) +{ + u_int8_t adjust = 0; + + if (MP4AV_AacConfigGetSamplingRateIndex(pConfig) == 0xF) { + adjust = 3; + } + return (pConfig[1 + adjust] >> 3) & 0xF; +} + +extern "C" bool MP4AV_AacGetConfigurationFromAdts( + u_int8_t** ppConfig, + u_int32_t* pConfigLength, + u_int8_t* pHdr) +{ + return MP4AV_AacGetConfiguration( + ppConfig, + pConfigLength, + MP4AV_AdtsGetProfile(pHdr), + MP4AV_AdtsGetSamplingRate(pHdr), + MP4AV_AdtsGetChannels(pHdr)); +} + +extern "C" bool MP4AV_AacGetConfiguration( + u_int8_t** ppConfig, + u_int32_t* pConfigLength, + u_int8_t profile, + u_int32_t samplingRate, + u_int8_t channels) +{ + /* create the appropriate decoder config */ + + u_int8_t* pConfig = (u_int8_t*)malloc(2); + + if (pConfig == NULL) { + return false; + } + + u_int8_t samplingRateIndex = + MP4AV_AdtsFindSamplingRateIndex(samplingRate); + + pConfig[0] = + ((profile + 1) << 3) | ((samplingRateIndex & 0xe) >> 1); + pConfig[1] = + ((samplingRateIndex & 0x1) << 7) | (channels << 3); + + /* LATER this option is not currently used in MPEG4IP + if (samplesPerFrame == 960) { + pConfig[1] |= (1 << 2); + } + */ + + *ppConfig = pConfig; + *pConfigLength = 2; + + return true; +} + +extern "C" bool MP4AV_AacGetConfiguration_SBR( + u_int8_t** ppConfig, + u_int32_t* pConfigLength, + u_int8_t profile, + u_int32_t samplingRate, + u_int8_t channels) +{ + /* create the appropriate decoder config */ + + u_int8_t* pConfig = (u_int8_t*)malloc(5); + if (pConfig == NULL) return false; + + pConfig[0] = 0; + pConfig[1] = 0; + pConfig[2] = 0; + pConfig[3] = 0; + pConfig[4] = 0; + + if (pConfig == NULL) { + return false; + } + + u_int8_t samplingRateIndex = + MP4AV_AdtsFindSamplingRateIndex(samplingRate); + + pConfig[0] = + ((profile + 1) << 3) | ((samplingRateIndex & 0xe) >> 1); + pConfig[1] = + ((samplingRateIndex & 0x1) << 7) | (channels << 3); + + /* pConfig[0] & pConfig[1] now contain the backward compatible + AudioSpecificConfig + */ + + /* SBR stuff */ + const u_int16_t syncExtensionType = 0x2B7; + u_int8_t extensionSamplingRateIndex = + MP4AV_AdtsFindSamplingRateIndex(2*samplingRate); + + pConfig[2] = (syncExtensionType >> 3) & 0xFF; + pConfig[3] = ((syncExtensionType & 0x7) << 5) | 5 /* ext ot id */; + pConfig[4] = ((1 & 0x1) << 7) | (extensionSamplingRateIndex << 3); + + *ppConfig = pConfig; + *pConfigLength = 5; + + return true; +} + +extern "C" void MP4AV_LatmGetConfiguration (uint8_t **ppConfig, + uint32_t *pConfigLength, + const uint8_t *AudioSpecificConfig, + uint32_t AudioSpecificConfigLen) +{ + *ppConfig = NULL; + *pConfigLength = 0; + uint32_t ix; + uint8_t *stream_mux_config = (uint8_t *)malloc(AudioSpecificConfigLen + 2 + 3); + if (stream_mux_config == NULL) return; + + stream_mux_config[0] = 0x80; + stream_mux_config[1] = 0; + for (ix = 0; ix < AudioSpecificConfigLen; ix++) { + stream_mux_config[ix + 1] |= (AudioSpecificConfig[ix] >> 7) & 0x1; + stream_mux_config[ix + 2] = AudioSpecificConfig[ix] << 1; + } + stream_mux_config[ix + 2] = 0x3f; + stream_mux_config[ix + 3] = 0xc0; + *ppConfig = stream_mux_config; + *pConfigLength = ix + 3; +} + +extern "C" bool MP4AV_AacGetConfiguration_LATM ( + u_int8_t** ppConfig, + u_int32_t* pConfigLength, + u_int8_t profile, + u_int32_t samplingRate, + u_int8_t channels) +{ + /* create the appropriate config string */ + + u_int8_t* pConfig = (u_int8_t*)malloc(6); + + if (pConfig == NULL) { + return false; + } + + u_int8_t samplingRateIndex = MP4AV_AdtsFindSamplingRateIndex(samplingRate); + + // StreamMuxConfig + pConfig[0] = 0x40; + pConfig[1] = ((profile+1 & 0x10) >> 5); + + pConfig[2] = (((profile + 1) & 0x0f) << 4) | (samplingRateIndex & 0x0f); + + pConfig[3] = (channels << 4); + pConfig[4] = 0x3f; + pConfig[5] = 0xc0; + + + *ppConfig = pConfig; + *pConfigLength = 6; + + return true; +} + + +#define ADTS_HEADER_MAX_SIZE 10 /* bytes */ + +static u_int8_t firstHeader[ADTS_HEADER_MAX_SIZE]; +static u_int16_t OLD_MP4AV_AdtsGetFrameSize(u_int8_t* pHdr) +{ + /* extract the necessary fields from the header */ + u_int8_t isMpeg4 = !(pHdr[1] & 0x08); + u_int16_t frameLength; + + if (isMpeg4) { + frameLength = (((u_int16_t)pHdr[4]) << 5) | (pHdr[5] >> 3); + } else { /* MPEG-2 */ + frameLength = (((u_int16_t)(pHdr[3] & 0x3)) << 11) + | (((u_int16_t)pHdr[4]) << 3) | (pHdr[5] >> 5); + } + + return frameLength; +} +static u_int16_t OLD_MP4AV_AdtsGetHeaderBitSize(u_int8_t* pHdr) +{ + u_int8_t isMpeg4 = !(pHdr[1] & 0x08); + u_int8_t hasCrc = !(pHdr[1] & 0x01); + u_int16_t hdrSize; + + if (isMpeg4) { + hdrSize = 58; + } else { + hdrSize = 56; + } + if (hasCrc) { + hdrSize += 16; + } + return hdrSize; +} + +static u_int16_t OLD_MP4AV_AdtsGetHeaderByteSize(u_int8_t* pHdr) +{ + return (OLD_MP4AV_AdtsGetHeaderBitSize(pHdr) + 7) / 8; +} + +/* + * hdr must point to at least ADTS_HEADER_MAX_SIZE bytes of memory + */ +static bool LoadNextAdtsHeader(FILE* inFile, u_int8_t* hdr) +{ + u_int state = 0; + u_int dropped = 0; + u_int hdrByteSize = ADTS_HEADER_MAX_SIZE; + + while (1) { + /* read a byte */ + u_int8_t b; + + if (fread(&b, 1, 1, inFile) == 0) { + return false; + } + + /* header is complete, return it */ + if (state == hdrByteSize - 1) { + hdr[state] = b; + if (dropped > 0) { +#ifdef DEBUG + fprintf(stderr, "Warning: dropped %u input bytes at offset %ld\n", dropped, + ftell(inFile) - dropped - state - 1); +#endif + } + return true; + } + + /* collect requisite number of bytes, no constraints on data */ + if (state >= 2) { + hdr[state++] = b; + } else { + /* have first byte, check if we have 1111X00X */ + if (state == 1) { + if ((b & 0xF6) == 0xF0) { + hdr[state] = b; + state = 2; + /* compute desired header size */ + if (aacUseOldFile) { + hdrByteSize = OLD_MP4AV_AdtsGetHeaderByteSize(hdr); + } else { + hdrByteSize = MP4AV_AdtsGetHeaderByteSize(hdr); + } + } else { + state = 0; + dropped ++; + } + } + /* initial state, looking for 11111111 */ + if (state == 0) { + if (b == 0xFF) { + hdr[state] = b; + state = 1; + } else { + /* else drop it */ + dropped++; + // printf("%02x ", b); + } + } + } + } +} + +/* + * Load the next frame from the file + * into the supplied buffer, which better be large enough! + * + * Note: Frames are padded to byte boundaries + */ +static bool LoadNextAacFrame(FILE* inFile, u_int8_t* pBuf, u_int32_t* pBufSize, bool stripAdts) +{ + u_int16_t frameSize; + u_int16_t hdrBitSize, hdrByteSize; + u_int8_t hdrBuf[ADTS_HEADER_MAX_SIZE]; + + /* get the next AAC frame header, more or less */ + if (!LoadNextAdtsHeader(inFile, hdrBuf)) { + return false; + } + + /* get frame size from header */ + if (aacUseOldFile) { + frameSize = OLD_MP4AV_AdtsGetFrameSize(hdrBuf); + /* get header size in bits and bytes from header */ + hdrBitSize = OLD_MP4AV_AdtsGetHeaderBitSize(hdrBuf); + hdrByteSize = OLD_MP4AV_AdtsGetHeaderByteSize(hdrBuf); + } else { + frameSize = MP4AV_AdtsGetFrameSize(hdrBuf); + /* get header size in bits and bytes from header */ + hdrBitSize = MP4AV_AdtsGetHeaderBitSize(hdrBuf); + hdrByteSize = MP4AV_AdtsGetHeaderByteSize(hdrBuf); + } + + + /* adjust the frame size to what remains to be read */ + frameSize -= hdrByteSize; + + if (stripAdts) { + if ((hdrBitSize % 8) == 0) { + /* header is byte aligned, i.e. MPEG-2 ADTS */ + /* read the frame data into the buffer */ + if (fread(pBuf, 1, frameSize, inFile) != frameSize) { + return false; + } + (*pBufSize) = frameSize; + } else { + /* header is not byte aligned, i.e. MPEG-4 ADTS */ + int i; + u_int8_t newByte; + int upShift = hdrBitSize % 8; + int downShift = 8 - upShift; + + pBuf[0] = hdrBuf[hdrBitSize / 8] << upShift; + + for (i = 0; i < frameSize; i++) { + if (fread(&newByte, 1, 1, inFile) != 1) { + return false; + } + pBuf[i] |= (newByte >> downShift); + pBuf[i+1] = (newByte << upShift); + } + (*pBufSize) = frameSize + 1; + } + } else { /* don't strip ADTS headers */ + memcpy(pBuf, hdrBuf, hdrByteSize); + if (fread(&pBuf[hdrByteSize], 1, frameSize, inFile) != frameSize) { + return false; + } + } + + return true; +} + +static bool GetFirstHeader(FILE* inFile) +{ + /* read file until we find an audio frame */ + fpos_t curPos; + + /* already read first header */ + if (firstHeader[0] == 0xff) { + return true; + } + + /* remember where we are */ + fgetpos(inFile, &curPos); + + /* go back to start of file */ + rewind(inFile); + + if (!LoadNextAdtsHeader(inFile, firstHeader)) { + return false; + } + + /* reposition the file to where we were */ + fsetpos(inFile, &curPos); + + return true; +} + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError +{ + if ((self = [super init])) { + _fileURL = [fileURL retain]; + + _tracksArray = [[NSMutableArray alloc] initWithCapacity:1]; + + MP42Track *newTrack = [[MP42AudioTrack alloc] init]; + + newTrack.format = MP42AudioFormatAAC; + newTrack.sourceURL = _fileURL; + + if (!inFile) + inFile = fopen([[_fileURL path] UTF8String], "rb"); + + struct stat st; + stat([[_fileURL path] UTF8String], &st); + size = st.st_size * 8; + + // collect all the necessary meta information + u_int8_t mpegVersion; + u_int8_t profile; + u_int8_t channelConfig; + + if (!GetFirstHeader(inFile)) { + //*outError = MP42Error(@"The audio could not be opened.", @"Data in file doesn't appear to be valid audio.", 100); + [newTrack release]; + return nil; + } + + samplesPerSecond = MP4AV_AdtsGetSamplingRate(firstHeader); + mpegVersion = MP4AV_AdtsGetVersion(firstHeader); + profile = MP4AV_AdtsGetProfile(firstHeader); + if (aacProfileLevel == 2) { + if (profile > MP4_MPEG4_AAC_SSR_AUDIO_TYPE) { + //*outError = MP42Error(@"The audio could not be opened.", @"Can't convert profile to mpeg2", 100); + [newTrack release]; + return nil; + } + mpegVersion = 1; + } else if (aacProfileLevel == 4) { + mpegVersion = 0; + } + channelConfig = MP4AV_AdtsGetChannels(firstHeader); + + u_int8_t audioType = MP4_INVALID_AUDIO_TYPE; + switch (mpegVersion) { + case 0: + audioType = MP4_MPEG4_AUDIO_TYPE; + break; + case 1: + switch (profile) { + case 0: + audioType = MP4_MPEG2_AAC_MAIN_AUDIO_TYPE; + break; + case 1: + audioType = MP4_MPEG2_AAC_LC_AUDIO_TYPE; + break; + case 2: + audioType = MP4_MPEG2_AAC_SSR_AUDIO_TYPE; + break; + case 3: + //*outError = MP42Error(@"The audio could not be opened.", @"Data in file doesn't appear to be valid audio.", 100); + [newTrack release]; + return nil; + default: + break; + } + break; + default: + break; + } + + u_int8_t* pConfig = NULL; + u_int32_t configLength = 0; + + MP4AV_AacGetConfiguration( + &pConfig, + &configLength, + profile, + samplesPerSecond, + channelConfig); + + [(MP42AudioTrack*) newTrack setChannels:channelConfig]; + [newTrack setDataLength:[[[[NSFileManager defaultManager] attributesOfItemAtPath:[_fileURL path] error:nil] valueForKey:NSFileSize] unsignedLongLongValue]]; + + aacInfo = [[NSMutableData alloc] init]; + [aacInfo appendBytes:pConfig length:configLength]; + free(pConfig); + + [_tracksArray addObject:newTrack]; + [newTrack release]; + } + + return self; +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + return samplesPerSecond; +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + return NSMakeSize([(MP42SubtitleTrack*)track trackWidth], [(MP42SubtitleTrack*) track trackHeight]); +} + +- (NSData*)magicCookieForTrack:(MP42Track *)track +{ + return aacInfo; +} + +- (void)demux:(id)sender +{ + @autoreleasepool { + if (!inFile) + inFile = fopen([[_fileURL path] UTF8String], "rb"); + + MP4TrackId trackId = [[_inputTracks lastObject] sourceId]; + + // parse the ADTS frames, and write the MP4 samples + u_int8_t sampleBuffer[8 * 1024]; + u_int32_t sampleSize = sizeof(sampleBuffer); + MP4SampleId sampleId = 1; + + int64_t currentSize = 0; + + while (LoadNextAacFrame(inFile, sampleBuffer, &sampleSize, true) && !_cancelled) { + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + + void * sampleDataBuffer = malloc(sampleSize); + memcpy(sampleDataBuffer, sampleBuffer, sampleSize); + + sample->data = sampleDataBuffer; + sample->size = sampleSize; + sample->duration = MP4_INVALID_DURATION; + sample->offset = 0; + sample->timestamp = 0; + sample->isSync = 1; + sample->trackId = trackId; + + [self enqueue:sample]; + [sample release]; + + sampleId++; + sampleSize = sizeof(sampleBuffer); + + currentSize += sampleSize; + _progress = (currentSize / (CGFloat) size) * 100; + } + + [self setDone:YES]; + } +} + +- (void)startReading +{ + [super startReading]; + + if (!_demuxerThread && !_done) { + _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; + [_demuxerThread setName:@"AAC Demuxer"]; + [_demuxerThread start]; + } +} + +- (void) dealloc +{ + [aacInfo release]; + fclose(inFile); + + [super dealloc]; +} + +@end diff --git a/MP42/MP42AC3Importer.h b/MP42/MP42AC3Importer.h new file mode 100644 index 0000000..1b89d3c --- /dev/null +++ b/MP42/MP42AC3Importer.h @@ -0,0 +1,20 @@ +// +// MP42AC3FileImporter.h +// Subler +// +// Created by Damiano Galassi on 07/12/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import +#import "MP42FileImporter.h" + +@interface MP42AC3Importer : MP42FileImporter { + FILE* inFile; + int64_t size; + + NSMutableData *ac3Info; + u_int32_t samplesPerSecond; +} + +@end \ No newline at end of file diff --git a/MP42/MP42AC3Importer.m b/MP42/MP42AC3Importer.m new file mode 100644 index 0000000..9bad2de --- /dev/null +++ b/MP42/MP42AC3Importer.m @@ -0,0 +1,401 @@ +// +// MP42AC3FileImporter.m +// Subler +// +// Created by Damiano Galassi on 07/12/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import "MP42AC3Importer.h" +#import "SBLanguages.h" +#import "MP42File.h" +#import "MP42Utilities.h" +#import "MP42Fifo.h" + +#include + +#define AC3_HEADER_MAX_SIZE 10 /* bytes */ +#define NUM_AC3_SAMPLING_RATES 4 +#define NUM_AC3_FRAMECODE_SIZES 19 * 2 + + +@implementation MP42AC3Importer + +u_int32_t Ac3SamplingRates[NUM_AC3_SAMPLING_RATES] = { + 48000, 44100, 32000, 0 +}; + +// Format(frmsizecod) +// Nominal bit rate (kbit/s), Words/syncframe (32 kHz), Words/syncframe (44.1 kHz), Words/syncframe (48 kHz) +u_int32_t Ac3FrameSize[NUM_AC3_FRAMECODE_SIZES][4] = { + {32, 96, 69, 64}, + {32, 96, 70, 64}, + {40, 120, 87, 80}, + {40, 120, 88, 80}, + {48, 144, 104, 96}, + {48, 144, 105, 96}, + {56, 168, 121, 112}, + {56, 168, 122, 112}, + {64, 192, 139, 128}, + {64, 192, 140, 128}, + {80, 240, 174, 160}, + {80, 240, 175, 160}, + {96, 288, 208, 192}, + {96, 288, 209, 192}, + {112, 336, 243, 224}, + {112, 336, 244, 224}, + {128, 384, 278, 256}, + {128, 384, 279, 256}, + {160, 480, 348, 320}, + {160, 480, 349, 320}, + {192, 576, 417, 384}, + {192, 576, 418, 384}, + {224, 672, 487, 448}, + {224, 672, 488, 448}, + {256, 768, 557, 512}, + {256, 768, 558, 512}, + {320, 960, 696, 640}, + {320, 960, 697, 640}, + {384, 1152, 835, 768}, + {384, 1152, 836, 768}, + {448, 1344, 975, 896}, + {448, 1344, 976, 896}, + {512, 1536, 1114, 1024}, + {512, 1536, 1115, 1024}, + {576, 1728, 1253, 1152}, + {576, 1728, 1254, 1152}, + {640, 1920, 1393, 1280}, + {640, 1920, 1394, 1280}, +}; + +static u_int8_t firstHeader[AC3_HEADER_MAX_SIZE]; + +static u_int16_t MP4AV_Ac3GetHeaderBitSize(u_int8_t* pHdr) +{ + return AC3_HEADER_MAX_SIZE * 8; +} + +static u_int16_t MP4AV_Ac3GetHeaderByteSize(u_int8_t* pHdr) +{ + return AC3_HEADER_MAX_SIZE; +} + +static u_int8_t MP4AV_Ac3GetSamplingRateIndex(u_int8_t* pHdr) +{ + return ((pHdr[4] & 0xC0) >> 6); +} + +static u_int32_t MP4AV_Ac3GetSamplingRate(u_int8_t* pHdr) +{ + return Ac3SamplingRates[MP4AV_Ac3GetSamplingRateIndex(pHdr)]; +} + +static u_int8_t MP4AV_Ac3GetFrameSizeCode(u_int8_t* pHdr) +{ + return (pHdr[4] & 0x3F); +} + +static u_int16_t MP4AV_Ac3GetFrameSize(u_int8_t* pHdr) +{ + u_int8_t index = MP4AV_Ac3GetSamplingRateIndex(pHdr); + u_int8_t frmsizecod = MP4AV_Ac3GetFrameSizeCode(pHdr); + // table returns words + return Ac3FrameSize[frmsizecod][3 - index] * 2; +} + +/* + * hdr must point to at least Ac3_HEADER_MAX_SIZE bytes of memory + */ +static bool LoadNextAc3Header(FILE* inFile, u_int8_t* hdr) +{ + u_int state = 0; + u_int dropped = 0; + u_int hdrByteSize = AC3_HEADER_MAX_SIZE; + + while (1) { + /* read a byte */ + u_int8_t b; + + if (fread(&b, 1, 1, inFile) == 0) { + return false; + } + + /* header is complete, return it */ + if (state == hdrByteSize - 1) { + hdr[state] = b; + if (dropped > 0) { +#ifdef DEBUG + fprintf(stderr, "Warning: dropped %u input bytes at offset %ld\n", dropped, + ftell(inFile) - dropped - state - 1); +#endif + } + return true; + } + + /* collect requisite number of bytes, no constraints on data */ + if (state >= 2) { + hdr[state++] = b; + } else { + /* have first byte, check if we have 0111 0111 */ + if (state == 1) { + if (b == 0x77) { + hdr[state] = b; + state = 2; + /* compute desired header size */ + hdrByteSize = MP4AV_Ac3GetHeaderByteSize(hdr); + } else { + state = 0; + dropped ++; + } + } + /* initial state, looking for 0000 1011 */ + if (state == 0) { + if (b == 0x0B) { + hdr[state] = b; + state = 1; + } else { + /* else drop it */ + dropped++; + // printf("%02x ", b); + } + } + } + } +} + +/* + * Load the next frame from the file + * into the supplied buffer, which better be large enough! + * + * Note: Frames are padded to byte boundaries + */ +static bool LoadNextAc3Frame(FILE* inFile, u_int8_t* pBuf, u_int32_t* pBufSize, bool stripAc3) +{ + u_int16_t frameSize; + u_int16_t hdrBitSize, hdrByteSize; + u_int8_t hdrBuf[AC3_HEADER_MAX_SIZE]; + + /* get the next Ac3 frame header, more or less */ + if (!LoadNextAc3Header(inFile, hdrBuf)) { + return false; + } + + /* get frame size from header */ + frameSize = MP4AV_Ac3GetFrameSize(hdrBuf); + *pBufSize = frameSize; + /* get header size in bits and bytes from header */ + hdrBitSize = MP4AV_Ac3GetHeaderBitSize(hdrBuf); + hdrByteSize = MP4AV_Ac3GetHeaderByteSize(hdrBuf); + + /* adjust the frame size to what remains to be read */ + frameSize -= hdrByteSize; + + if (stripAc3) { + if ((hdrBitSize % 8) == 0) { + /* header is byte aligned, i.e. MPEG-2 Ac3 */ + /* read the frame data into the buffer */ + if (fread(pBuf, 1, frameSize, inFile) != frameSize) { + return false; + } + (*pBufSize) = frameSize; + } else { + /* header is not byte aligned, i.e. MPEG-4 Ac3 */ + int i; + u_int8_t newByte; + int upShift = hdrBitSize % 8; + int downShift = 8 - upShift; + + pBuf[0] = hdrBuf[hdrBitSize / 8] << upShift; + + for (i = 0; i < frameSize; i++) { + if (fread(&newByte, 1, 1, inFile) != 1) { + return false; + } + pBuf[i] |= (newByte >> downShift); + pBuf[i+1] = (newByte << upShift); + } + (*pBufSize) = frameSize + 1; + } + } else { /* don't strip Ac3 headers */ + memcpy(pBuf, hdrBuf, hdrByteSize); + if (fread(&pBuf[hdrByteSize], 1, frameSize, inFile) != frameSize) { + return false; + } + } + + return true; +} + +static bool GetFirstHeader(FILE* inFile) +{ + /* read file until we find an audio frame */ + fpos_t curPos; + + /* already read first header */ + /*if (firstHeader[0] == 0x0b) { + return true; + }*/ + + /* remember where we are */ + fgetpos(inFile, &curPos); + + /* go back to start of file */ + rewind(inFile); + + if (!LoadNextAc3Header(inFile, firstHeader)) { + return false; + } + + /* reposition the file to where we were */ + fsetpos(inFile, &curPos); + + return true; +} + + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError +{ + if ((self = [super init])) { + _fileURL = [fileURL retain]; + + _tracksArray = [[NSMutableArray alloc] initWithCapacity:1]; + + MP42AudioTrack *newTrack = [[MP42AudioTrack alloc] init]; + + newTrack.format = MP42AudioFormatAC3; + newTrack.sourceURL = _fileURL; + + if (!inFile) + inFile = fopen([[_fileURL path] UTF8String], "rb"); + + struct stat st; + stat([[_fileURL path] UTF8String], &st); + size = st.st_size * 8; + + // collect all the necessary meta information + UInt32 channels = 0, channelLayoutTag = 0; + uint32_t fscod, frmsizecod, bsid, bsmod, acmod, lfeon; + uint32_t lfe_offset = 4; + + if (!GetFirstHeader(inFile)) { + fprintf(stderr, + "Subler: data in file doesn't appear to be valid ac3 audio\n"); + } + + fscod = (firstHeader[4] >> 6) & 0x3; + frmsizecod = (firstHeader[4] & 0x3f); + bsid = (firstHeader[5] >> 3) & 0x1f; + bsmod = (firstHeader[5] & 0xf); + acmod = (firstHeader[6] >> 5) & 0x7; + if (acmod == 2) + lfe_offset -= 2; + else { + if ((acmod & 1) && acmod != 1) + lfe_offset -= 2; + if (acmod & 4) + lfe_offset -= 2; + } + lfeon = (firstHeader[6] >> lfe_offset) & 0x1; + + samplesPerSecond = MP4AV_Ac3GetSamplingRate(firstHeader); + + readAC3Config(acmod, lfeon, &channels, &channelLayoutTag); + + [newTrack setChannels:channels]; + [newTrack setChannelLayoutTag:channelLayoutTag]; + + ac3Info = [[NSMutableData alloc] init]; + [ac3Info appendBytes:&fscod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsid length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&acmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&lfeon length:sizeof(uint64_t)]; + [ac3Info appendBytes:&frmsizecod length:sizeof(uint64_t)]; + + [newTrack setDataLength:[[[[NSFileManager defaultManager] attributesOfItemAtPath:[_fileURL path] error:nil] valueForKey:NSFileSize] unsignedLongLongValue]]; + + [_tracksArray addObject:newTrack]; + [newTrack release]; + } + + return self; +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + return samplesPerSecond; +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + return NSMakeSize([(MP42SubtitleTrack*)track trackWidth], [(MP42SubtitleTrack*) track trackHeight]); +} + +- (NSData*)magicCookieForTrack:(MP42Track *)track +{ + return ac3Info; +} + +- (void)demux:(id)sender +{ + @autoreleasepool { + if (!inFile) + inFile = fopen([[_fileURL path] UTF8String], "rb"); + + MP4TrackId trackId = [[_inputTracks lastObject] sourceId]; + + // parse the Ac3 frames, and write the MP4 samples + u_int8_t sampleBuffer[8 * 1024]; + u_int32_t sampleSize = sizeof(sampleBuffer); + MP4SampleId sampleId = 1; + + int64_t currentSize = 0; + + while (LoadNextAc3Frame(inFile, sampleBuffer, &sampleSize, false) && !_cancelled) { + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + + void * sampleDataBuffer = malloc(sampleSize); + memcpy(sampleDataBuffer, sampleBuffer, sampleSize); + + sample->data = sampleDataBuffer; + sample->size = sampleSize; + sample->duration = MP4_INVALID_DURATION; + sample->offset = 0; + sample->timestamp = 0; + sample->isSync = 1; + sample->trackId = trackId; + + [self enqueue:sample]; + [sample release]; + + sampleId++; + sampleSize = sizeof(sampleBuffer); + + currentSize += sampleSize; + _progress = (currentSize / (CGFloat) size) * 100; + } + + [self setDone:YES]; + } +} + +- (void)startReading +{ + [super startReading]; + + if (!_demuxerThread && !_done) { + _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; + [_demuxerThread setName:@"AC-3 Demuxer"]; + [_demuxerThread start]; + } +} + +- (void) dealloc +{ + [ac3Info release]; + fclose(inFile); + + [super dealloc]; +} + +@end diff --git a/MP42/MP42AVFImporter.h b/MP42/MP42AVFImporter.h new file mode 100644 index 0000000..f9cf466 --- /dev/null +++ b/MP42/MP42AVFImporter.h @@ -0,0 +1,18 @@ +// +// MP42MkvFileImporter.h +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import +#import "MP42FileImporter.h" +@class AVAsset; + +@interface MP42AVFImporter : MP42FileImporter { + AVAsset *_localAsset; +} + +@end + diff --git a/MP42/MP42AVFImporter.m b/MP42/MP42AVFImporter.m new file mode 100644 index 0000000..7d8f837 --- /dev/null +++ b/MP42/MP42AVFImporter.m @@ -0,0 +1,1012 @@ +// +// MP42MkvFileImporter.m +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#if __MAC_OS_X_VERSION_MAX_ALLOWED > 1060 + +#import "MP42AVFImporter.h" +#import "SBLanguages.h" +#import "MP42File.h" +#import "MP42Image.h" + +#import +#import + +@interface AVFDemuxHelper : NSObject { +@public + BOOL countFrames; + int64_t correctionValue; + int64_t disTimeStamp; + CMTimeRange *discontinuity; + uint64_t discontinuityCount; + BOOL doNotDisplay; + CMTime currentTime; + CMTime segmentEndTimestamp; + CMTime segmentDuration; + CMTime segmentStarTime; + AVAssetReaderOutput *assetReaderOutput; + int64_t minDisplayOffset; +} +@end + +@implementation AVFDemuxHelper +@end + +@implementation MP42AVFImporter + +- (NSString*)formatForTrack: (AVAssetTrack *)track; +{ + NSString* result = @""; + + CMFormatDescriptionRef formatDescription = NULL; + NSArray *formatDescriptions = track.formatDescriptions; + if ([formatDescriptions count] > 0) + formatDescription = (CMFormatDescriptionRef)[formatDescriptions objectAtIndex:0]; + + if (formatDescription) { + FourCharCode code = CMFormatDescriptionGetMediaSubType(formatDescription); + switch (code) { + case kCMVideoCodecType_H264: + result = MP42VideoFormatH264; + break; + case kCMVideoCodecType_MPEG4Video: + result = MP42VideoFormatMPEG4Visual; + break; + case kCMVideoCodecType_MPEG2Video: + result = MP42VideoFormatMPEG2; + break; + case kCMVideoCodecType_MPEG1Video: + result = MP42VideoFormatMPEG1; + break; + case kCMVideoCodecType_AppleProRes422: + case kCMVideoCodecType_AppleProRes422HQ: + case kCMVideoCodecType_AppleProRes422LT: + case kCMVideoCodecType_AppleProRes422Proxy: + case kCMVideoCodecType_AppleProRes4444: + result = MP42VideoFormatProRes; + break; + case kCMVideoCodecType_SorensonVideo3: + result = MP42VideoFormatSorenson3; + break; + case 'png ': + result = MP42VideoFormatPNG; + break; + case kAudioFormatMPEG4AAC: + result = MP42AudioFormatAAC; + break; + case kAudioFormatMPEG4AAC_HE: + case kAudioFormatMPEG4AAC_HE_V2: + result = MP42AudioFormatHEAAC; + break; + case kAudioFormatLinearPCM: + result = MP42AudioFormatPCM; + break; + case kAudioFormatAppleLossless: + result = MP42AudioFormatALAC; + break; + case kAudioFormatAC3: + case 'ms \0': + result = MP42AudioFormatAC3; + break; + case kAudioFormatMPEGLayer1: + case kAudioFormatMPEGLayer2: + case kAudioFormatMPEGLayer3: + result = MP42AudioFormatMP3; + break; + case kAudioFormatAMR: + result = MP42AudioFormatAMR; + break; + case kAudioFormatAppleIMA4: + result = @"IMA 4:1"; + break; + case kCMTextFormatType_QTText: + result = MP42SubtitleFormatText; + break; + case kCMTextFormatType_3GText: + result = MP42SubtitleFormatTx3g; + break; + case 'SRT ': + result = MP42SubtitleFormatText; + break; + case 'SSA ': + result = MP42SubtitleFormatSSA; + break; + case kCMClosedCaptionFormatType_CEA608: + result = MP42ClosedCaptionFormatCEA608; + break; + case kCMClosedCaptionFormatType_CEA708: + result = MP42ClosedCaptionFormatCEA708; + break; + case kCMClosedCaptionFormatType_ATSC: + result = @"ATSC/52 part-4"; + break; + case kCMTimeCodeFormatType_TimeCode32: + case kCMTimeCodeFormatType_TimeCode64: + case kCMTimeCodeFormatType_Counter32: + case kCMTimeCodeFormatType_Counter64: + result = MP42TimeCodeFormat; + break; + case kCMVideoCodecType_JPEG: + result = MP42VideoFormatJPEG; + break; + case kCMVideoCodecType_DVCNTSC: + case kCMVideoCodecType_DVCPAL: + result = MP42VideoFormatDV; + break; + case kCMVideoCodecType_DVCProPAL: + case kCMVideoCodecType_DVCPro50NTSC: + case kCMVideoCodecType_DVCPro50PAL: + result = @"DVCPro"; + break; + case kCMVideoCodecType_DVCPROHD720p60: + case kCMVideoCodecType_DVCPROHD720p50: + case kCMVideoCodecType_DVCPROHD1080i60: + case kCMVideoCodecType_DVCPROHD1080i50: + case kCMVideoCodecType_DVCPROHD1080p30: + case kCMVideoCodecType_DVCPROHD1080p25: + result = @"DVCProHD"; + break; + default: + result = @"Unknown"; + break; + } + } + return result; +} + +- (NSString*)langForTrack: (AVAssetTrack *)track +{ + return [NSString stringWithUTF8String:lang_for_qtcode([[track languageCode] integerValue])->eng_name]; +} + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError +{ + if ((self = [super init])) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + _fileURL = [fileURL retain]; + _localAsset = [[AVAsset assetWithURL:_fileURL] retain]; + + _tracksArray = [[NSMutableArray alloc] init]; + NSArray *tracks = [_localAsset tracks]; + + NSArray *availableChapter = [_localAsset availableChapterLocales]; + MP42ChapterTrack *chapters = nil; + + if ([tracks count]) { + for (NSLocale *locale in availableChapter) { + chapters = [[MP42ChapterTrack alloc] init]; + NSArray *chapterList = [_localAsset chapterMetadataGroupsWithTitleLocale:locale containingItemsWithCommonKeys:nil]; + for (AVTimedMetadataGroup* chapterData in chapterList) { + for (AVMetadataItem *item in [chapterData items]) { + CMTime time = [item time]; + [chapters addChapter:[item stringValue] duration:time.value * time.timescale / 1000]; + } + } + } + } + + for (AVAssetTrack *track in tracks) { + MP42Track *newTrack = nil; + + CMFormatDescriptionRef formatDescription = NULL; + NSArray *formatDescriptions = track.formatDescriptions; + if ([formatDescriptions count] > 0) + formatDescription = (CMFormatDescriptionRef)[formatDescriptions objectAtIndex:0]; + + NSArray *trackMetadata = [track metadataForFormat:AVMetadataFormatQuickTimeUserData]; + + if ([[track mediaType] isEqualToString:AVMediaTypeVideo]) { + newTrack = [[MP42VideoTrack alloc] init]; + CGSize naturalSize = [track naturalSize]; + + [(MP42VideoTrack*)newTrack setTrackWidth: naturalSize.width]; + [(MP42VideoTrack*)newTrack setTrackHeight: naturalSize.height]; + + [(MP42VideoTrack*)newTrack setWidth: naturalSize.width]; + [(MP42VideoTrack*)newTrack setHeight: naturalSize.height]; + + if (formatDescription) { + CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription); + [(MP42VideoTrack*)newTrack setWidth: dimensions.width]; + [(MP42VideoTrack*)newTrack setHeight: dimensions.height]; + + CFDictionaryRef pixelAspectRatioFromCMFormatDescription = CMFormatDescriptionGetExtension(formatDescription, kCMFormatDescriptionExtension_PixelAspectRatio); + if (pixelAspectRatioFromCMFormatDescription) { + NSInteger hSpacing, vSpacing; + CFNumberGetValue(CFDictionaryGetValue(pixelAspectRatioFromCMFormatDescription, kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing), kCFNumberIntType, &hSpacing); + CFNumberGetValue(CFDictionaryGetValue(pixelAspectRatioFromCMFormatDescription, kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing), kCFNumberIntType, &vSpacing); + [(MP42VideoTrack*)newTrack setHSpacing:hSpacing]; + [(MP42VideoTrack*)newTrack setVSpacing:vSpacing]; + } + } + } + else if ([[track mediaType] isEqualToString:AVMediaTypeAudio]) { + newTrack = [[MP42AudioTrack alloc] init]; + + if (formatDescription) { + size_t layoutSize = 0; + const AudioChannelLayout *layout = CMAudioFormatDescriptionGetChannelLayout(formatDescription, &layoutSize); + + if (layoutSize) { + [(MP42AudioTrack*)newTrack setChannels: AudioChannelLayoutTag_GetNumberOfChannels(layout->mChannelLayoutTag)]; + [(MP42AudioTrack*)newTrack setChannelLayoutTag: layout->mChannelLayoutTag]; + } + else + [(MP42AudioTrack*)newTrack setChannels: 1]; + } + } + else if ([[track mediaType] isEqualToString:AVMediaTypeSubtitle]) { + newTrack = [[MP42SubtitleTrack alloc] init]; + } + else if ([[track mediaType] isEqualToString:AVMediaTypeText]) { + // It looks like there is no way to know what text track is used for chapters in the original file. + if (chapters) + newTrack = chapters; + else + newTrack = [[MP42ChapterTrack alloc] init]; + } + else { + newTrack = [[MP42Track alloc] init]; + } + + newTrack.format = [self formatForTrack:track]; + newTrack.Id = [track trackID]; + newTrack.sourceURL = _fileURL; + newTrack.dataLength = [track totalSampleDataLength]; + + // "name" is undefined in AVMetadataFormat.h, so read the official track name "tnam", and then "name". On 10.7, "name" is returned as an NSData + id trackName = [[[AVMetadataItem metadataItemsFromArray:trackMetadata withKey:AVMetadataQuickTimeUserDataKeyTrackName keySpace:nil] lastObject] value]; + id trackName_oldFormat = [[[AVMetadataItem metadataItemsFromArray:trackMetadata withKey:@"name" keySpace:nil] lastObject] value]; + if (trackName && [trackName isKindOfClass:[NSString class]]) + newTrack.name = trackName; + else if (trackName_oldFormat && [trackName_oldFormat isKindOfClass:[NSString class]]) + newTrack.name = trackName_oldFormat; + else if (trackName_oldFormat && [trackName_oldFormat isKindOfClass:[NSData class]]) + newTrack.name = [NSString stringWithCString:[trackName_oldFormat bytes] encoding:NSMacOSRomanStringEncoding]; + + newTrack.language = [self langForTrack:track]; + + CMTimeRange timeRange = [track timeRange]; + newTrack.duration = timeRange.duration.value / timeRange.duration.timescale * 1000; + + [_tracksArray addObject:newTrack]; + [newTrack release]; + } + + [self convertMetadata]; + + [pool release]; + } + + return self; +} + +-(void)convertMetadata +{ + NSArray *items = nil; + NSDictionary *commonItemsDict = [NSDictionary dictionaryWithObjectsAndKeys:@"Name", AVMetadataCommonKeyTitle, + //nil, AVMetadataCommonKeyCreator, + //nil, AVMetadataCommonKeySubject, + @"Description", AVMetadataCommonKeyDescription, + @"Publisher", AVMetadataCommonKeyPublisher, + //nil, AVMetadataCommonKeyContributor, + @"Release Date", AVMetadataCommonKeyCreationDate, + //nil, AVMetadataCommonKeyLastModifiedDate, + @"Genre", AVMetadataCommonKeyType, + //nil, AVMetadataCommonKeyFormat, + //nil, AVMetadataCommonKeyIdentifier, + //nil, AVMetadataCommonKeySource, + //nil, AVMetadataCommonKeyLanguage, + //nil, AVMetadataCommonKeyRelation, + //nil, AVMetadataCommonKeyLocation, + @"Copyright", AVMetadataCommonKeyCopyrights, + @"Album", AVMetadataCommonKeyAlbumName, + //nil, AVMetadataCommonKeyAuthor, + //nil, AVMetadataCommonKeyArtwork + @"Artist", AVMetadataCommonKeyArtist, + //nil, AVMetadataCommonKeyMake, + //nil, AVMetadataCommonKeyModel, + @"Encoding Tool", AVMetadataCommonKeySoftware, + nil]; + + _metadata = [[MP42Metadata alloc] init]; + + for (NSString *commonKey in [commonItemsDict allKeys]) { + items = [AVMetadataItem metadataItemsFromArray:_localAsset.commonMetadata withKey:commonKey keySpace:AVMetadataKeySpaceCommon]; + if ([items count]) + [_metadata setTag:[[items lastObject] value] forKey:[commonItemsDict objectForKey:commonKey]]; + } + + items = [AVMetadataItem metadataItemsFromArray:_localAsset.commonMetadata withKey:AVMetadataCommonKeyArtwork keySpace:AVMetadataKeySpaceCommon]; + if ([items count]) { + id artworkData = [[items lastObject] value]; + if ([artworkData isKindOfClass:[NSData class]]) { + NSImage *image = [[NSImage alloc] initWithData:artworkData]; + [_metadata.artworks addObject:[[[MP42Image alloc] initWithImage:image] autorelease]]; + [image release]; + } + } + + NSArray* availableMetadataFormats = [_localAsset availableMetadataFormats]; + + if ([availableMetadataFormats containsObject:AVMetadataFormatiTunesMetadata]) { + NSArray* itunesMetadata = [_localAsset metadataForFormat:AVMetadataFormatiTunesMetadata]; + + NSDictionary *itunesMetadataDict = [NSDictionary dictionaryWithObjectsAndKeys: + @"Album", AVMetadataiTunesMetadataKeyAlbum, + @"Artist", AVMetadataiTunesMetadataKeyArtist, + @"Comments", AVMetadataiTunesMetadataKeyUserComment, + //AVMetadataiTunesMetadataKeyCoverArt, + @"Copyright", AVMetadataiTunesMetadataKeyCopyright, + @"Release Date", AVMetadataiTunesMetadataKeyReleaseDate, + @"Encoded By", AVMetadataiTunesMetadataKeyEncodedBy, + //@"Genre", AVMetadataiTunesMetadataKeyPredefinedGenre, + @"Genre", AVMetadataiTunesMetadataKeyUserGenre, + @"Name", AVMetadataiTunesMetadataKeySongName, + @"Track Sub-Title", AVMetadataiTunesMetadataKeyTrackSubTitle, + @"Encoding Tool", AVMetadataiTunesMetadataKeyEncodingTool, + @"Composer", AVMetadataiTunesMetadataKeyComposer, + @"Album Artist", AVMetadataiTunesMetadataKeyAlbumArtist, + @"iTunes Account Type", AVMetadataiTunesMetadataKeyAccountKind, + @"iTunes Account", AVMetadataiTunesMetadataKeyAppleID, + @"artistID", AVMetadataiTunesMetadataKeyArtistID, + @"content ID", AVMetadataiTunesMetadataKeySongID, + @"Compilation", AVMetadataiTunesMetadataKeyDiscCompilation, + @"Disk #", AVMetadataiTunesMetadataKeyDiscNumber, + @"genreID", AVMetadataiTunesMetadataKeyGenreID, + @"Grouping", AVMetadataiTunesMetadataKeyGrouping, + @"playlistID", AVMetadataiTunesMetadataKeyPlaylistID, + @"Content Rating", AVMetadataiTunesMetadataKeyContentRating, + @"Rating", @"com.apple.iTunes.iTunEXTC", + @"Tempo", AVMetadataiTunesMetadataKeyBeatsPerMin, + @"Track #", AVMetadataiTunesMetadataKeyTrackNumber, + @"Art Director", AVMetadataiTunesMetadataKeyArtDirector, + @"Arranger", AVMetadataiTunesMetadataKeyArranger, + @"Lyricist", AVMetadataiTunesMetadataKeyAuthor, + @"Lyrics", AVMetadataiTunesMetadataKeyLyrics, + @"Acknowledgement", AVMetadataiTunesMetadataKeyAcknowledgement, + @"Conductor", AVMetadataiTunesMetadataKeyConductor, + @"Song Description", AVMetadataiTunesMetadataKeyDescription, + @"Description", @"desc", + @"Long Description", @"ldes", + @"Media Kind", @"stik", + @"TV Show", @"tvsh", + @"TV Episode #", @"tves", + @"TV Network", @"tvnn", + @"TV Episode ID", @"tven", + @"TV Season", @"tvsn", + @"HD Video", @"hdvd", + @"Gapless", @"pgap", + @"Sort Name", @"sonm", + @"Sort Artist", @"soar", + @"Sort Album Artist", @"soaa", + @"Sort Album", @"soal", + @"Sort Composer", @"soco", + @"Sort TV Show", @"sosn", + @"Category", @"catg", + @"iTunes U", @"itnu", + @"Purchase Date", @"purd", + @"Director", AVMetadataiTunesMetadataKeyDirector, + //AVMetadataiTunesMetadataKeyEQ, + @"Linear Notes", AVMetadataiTunesMetadataKeyLinerNotes, + @"Record Company", AVMetadataiTunesMetadataKeyRecordCompany, + @"Original Artist", AVMetadataiTunesMetadataKeyOriginalArtist, + @"Phonogram Rights", AVMetadataiTunesMetadataKeyPhonogramRights, + @"Producer", AVMetadataiTunesMetadataKeyProducer, + @"Performer", AVMetadataiTunesMetadataKeyPerformer, + @"Publisher", AVMetadataiTunesMetadataKeyPublisher, + @"Sound Engineer", AVMetadataiTunesMetadataKeySoundEngineer, + @"Soloist", AVMetadataiTunesMetadataKeySoloist, + @"Credits", AVMetadataiTunesMetadataKeyCredits, + @"Thanks", AVMetadataiTunesMetadataKeyThanks, + @"Online Extras", AVMetadataiTunesMetadataKeyOnlineExtras, + @"Executive Producer", AVMetadataiTunesMetadataKeyExecProducer, + nil]; + + for (NSString *itunesKey in [itunesMetadataDict allKeys]) { + items = [AVMetadataItem metadataItemsFromArray:itunesMetadata withKey:itunesKey keySpace:AVMetadataKeySpaceiTunes]; + if ([items count]) { + [_metadata setTag:[[items lastObject] value] forKey:[itunesMetadataDict objectForKey:itunesKey]]; + } + } + + items = [AVMetadataItem metadataItemsFromArray:itunesMetadata withKey:AVMetadataiTunesMetadataKeyCoverArt keySpace:AVMetadataKeySpaceiTunes]; + if ([items count]) { + id artworkData = [[items lastObject] value]; + if ([artworkData isKindOfClass:[NSData class]]) { + NSImage *image = [[NSImage alloc] initWithData:artworkData]; + [_metadata.artworks addObject:[[[MP42Image alloc] initWithImage:image] autorelease]]; + [image release]; + } + } + } + if ([availableMetadataFormats containsObject:AVMetadataFormatQuickTimeMetadata]) { + NSArray* quicktimeMetadata = [_localAsset metadataForFormat:AVMetadataFormatQuickTimeMetadata]; + + NSDictionary *quicktimeMetadataDict = [NSDictionary dictionaryWithObjectsAndKeys: + @"Arist", AVMetadataQuickTimeMetadataKeyAuthor, + @"Comments", AVMetadataQuickTimeMetadataKeyComment, + @"Copyright", AVMetadataQuickTimeMetadataKeyCopyright, + @"Release Date", AVMetadataQuickTimeMetadataKeyCreationDate, + @"Director", AVMetadataQuickTimeMetadataKeyDirector, + @"Name", AVMetadataQuickTimeMetadataKeyDisplayName, + @"Description", AVMetadataQuickTimeMetadataKeyInformation, + @"Keyworkds", AVMetadataQuickTimeMetadataKeyKeywords, + @"Producer", AVMetadataQuickTimeMetadataKeyProducer, + @"Publisher", AVMetadataQuickTimeMetadataKeyPublisher, + @"Album", AVMetadataQuickTimeMetadataKeyAlbum, + @"Artist", AVMetadataQuickTimeMetadataKeyArtist, + @"Description", AVMetadataQuickTimeMetadataKeyDescription, + @"Encoding Tool",AVMetadataQuickTimeMetadataKeySoftware, + @"Genre", AVMetadataQuickTimeMetadataKeyGenre, + //AVMetadataQuickTimeMetadataKeyiXML, + @"Arranger", AVMetadataQuickTimeMetadataKeyArranger, + @"Encoded By", AVMetadataQuickTimeMetadataKeyEncodedBy, + @"Original Artist", AVMetadataQuickTimeMetadataKeyOriginalArtist, + @"Performer", AVMetadataQuickTimeMetadataKeyPerformer, + @"Composer", AVMetadataQuickTimeMetadataKeyComposer, + @"Credits", AVMetadataQuickTimeMetadataKeyCredits, + @"Phonogram Rights", AVMetadataQuickTimeMetadataKeyPhonogramRights, + @"Name", AVMetadataQuickTimeMetadataKeyTitle, nil]; + + for (NSString *qtKey in [quicktimeMetadataDict allKeys]) { + items = [AVMetadataItem metadataItemsFromArray:quicktimeMetadata withKey:qtKey keySpace:AVMetadataKeySpaceQuickTimeUserData]; + if ([items count]) { + [_metadata setTag:[[items lastObject] value] forKey:[quicktimeMetadataDict objectForKey:qtKey]]; + } + } + } + if ([availableMetadataFormats containsObject:AVMetadataFormatQuickTimeUserData]) { + NSArray* quicktimeUserDataMetadata = [_localAsset metadataForFormat:AVMetadataFormatQuickTimeUserData]; + + NSDictionary *quicktimeUserDataMetadataDict = [NSDictionary dictionaryWithObjectsAndKeys: + @"Album", AVMetadataQuickTimeUserDataKeyAlbum, + @"Arranger", AVMetadataQuickTimeUserDataKeyArranger, + @"Artist", AVMetadataQuickTimeUserDataKeyArtist, + @"Lyricist", AVMetadataQuickTimeUserDataKeyAuthor, + @"Comments", AVMetadataQuickTimeUserDataKeyComment, + @"Composer", AVMetadataQuickTimeUserDataKeyComposer, + @"Copyright", AVMetadataQuickTimeUserDataKeyCopyright, + @"Release Date", AVMetadataQuickTimeUserDataKeyCreationDate, + @"Description", AVMetadataQuickTimeUserDataKeyDescription, + @"Director", AVMetadataQuickTimeUserDataKeyDirector, + @"Encoded By", AVMetadataQuickTimeUserDataKeyEncodedBy, + @"Name", AVMetadataQuickTimeUserDataKeyFullName, + @"Genre", AVMetadataQuickTimeUserDataKeyGenre, + @"Keywords", AVMetadataQuickTimeUserDataKeyKeywords, + @"Original Artist", AVMetadataQuickTimeUserDataKeyOriginalArtist, + @"Performer", AVMetadataQuickTimeUserDataKeyPerformers, + @"Producer", AVMetadataQuickTimeUserDataKeyProducer, + @"Publisher", AVMetadataQuickTimeUserDataKeyPublisher, + @"Online Extras", AVMetadataQuickTimeUserDataKeyURLLink, + @"Credits", AVMetadataQuickTimeUserDataKeyCredits, + @"Phonogram Rights", AVMetadataQuickTimeUserDataKeyPhonogramRights, nil]; + + for (NSString *qtUserDataKey in [quicktimeUserDataMetadataDict allKeys]) { + items = [AVMetadataItem metadataItemsFromArray:quicktimeUserDataMetadata withKey:qtUserDataKey keySpace:AVMetadataKeySpaceQuickTimeUserData]; + if ([items count]) { + [_metadata setTag:[[items lastObject] value] forKey:[quicktimeUserDataMetadataDict objectForKey:qtUserDataKey]]; + } + } + } +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + AVAssetTrack *assetTrack = [_localAsset trackWithTrackID:[track sourceId]]; + + CMFormatDescriptionRef formatDescription = NULL; + NSArray *formatDescriptions = assetTrack.formatDescriptions; + if ([formatDescriptions count] > 0) + formatDescription = (CMFormatDescriptionRef)[formatDescriptions objectAtIndex:0]; + if ([[assetTrack mediaType] isEqualToString:AVMediaTypeAudio]) { + const AudioStreamBasicDescription* const asbd = + CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription); + + double sampleRate = asbd->mSampleRate; + + return (NSUInteger)sampleRate; + } + + return [assetTrack naturalTimeScale]; +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + MP42VideoTrack* currentTrack = (MP42VideoTrack*) track; + + return NSMakeSize([currentTrack width], [currentTrack height]); +} + +- (NSData*)magicCookieForTrack:(MP42Track *)track +{ + AVAssetTrack *assetTrack = [_localAsset trackWithTrackID:[track sourceId]]; + + CMFormatDescriptionRef formatDescription = NULL; + NSArray *formatDescriptions = assetTrack.formatDescriptions; + if ([formatDescriptions count] > 0) + formatDescription = (CMFormatDescriptionRef)[formatDescriptions objectAtIndex:0]; + + if (formatDescription) { + FourCharCode code = CMFormatDescriptionGetMediaSubType(formatDescription); + if ([[assetTrack mediaType] isEqualToString:AVMediaTypeVideo]) { + CFDictionaryRef extentions = CMFormatDescriptionGetExtensions(formatDescription); + CFDictionaryRef atoms = CFDictionaryGetValue(extentions, kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms); + CFDataRef magicCookie = NULL; + + if (code == kCMVideoCodecType_H264) + magicCookie = CFDictionaryGetValue(atoms, @"avcC"); + else if (code == kCMVideoCodecType_MPEG4Video) + magicCookie = CFDictionaryGetValue(atoms, @"esds"); + + return (NSData*)magicCookie; + } + else if ([[assetTrack mediaType] isEqualToString:AVMediaTypeAudio]) { + + size_t cookieSizeOut; + const void *magicCookie = CMAudioFormatDescriptionGetMagicCookie(formatDescription, &cookieSizeOut); + + if (code == kAudioFormatMPEG4AAC || code == kAudioFormatMPEG4AAC_HE || code == kAudioFormatMPEG4AAC_HE_V2) { + // Extract DecoderSpecific info + UInt8* buffer; + int size; + ReadESDSDescExt((void*)magicCookie, &buffer, &size, 0); + + return [NSData dataWithBytes:buffer length:size]; + } + else if (code == kAudioFormatAppleLossless) { + if (cookieSizeOut > 48) { + // Remove unneeded parts of the cookie, as describred in ALACMagicCookieDescription.txt + magicCookie += 24; + cookieSizeOut = cookieSizeOut - 24 - 8; + } + + return [NSData dataWithBytes:magicCookie length:cookieSizeOut]; + } + else if (code == kAudioFormatAC3) { + OSStatus err = noErr; + size_t channelLayoutSize = 0; + const AudioStreamBasicDescription *asbd = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription); + const AudioChannelLayout* channelLayout = CMAudioFormatDescriptionGetChannelLayout(formatDescription, &channelLayoutSize); + + UInt32 bitmapSize = sizeof(UInt32); + UInt32 channelBitmap; + err = AudioFormatGetProperty(kAudioFormatProperty_BitmapForLayoutTag, + sizeof(AudioChannelLayoutTag), &channelLayout->mChannelLayoutTag, + &bitmapSize, &channelBitmap); + if (err && AudioChannelLayoutTag_GetNumberOfChannels(channelLayout->mChannelLayoutTag) == 6) + channelBitmap = 0x3F; + + uint8_t fscod = 0; + uint8_t bsid = 8; + uint8_t bsmod = 0; + uint8_t acmod = 7; + uint8_t lfeon = (channelBitmap & kAudioChannelBit_LFEScreen) ? 1 : 0; + uint8_t bit_rate_code = 15; + + switch (AudioChannelLayoutTag_GetNumberOfChannels(channelLayout->mChannelLayoutTag) - lfeon) { + case 1: + acmod = 1; + break; + case 2: + acmod = 2; + break; + case 3: + if (channelBitmap & kAudioChannelBit_CenterSurround) acmod = 3; + else acmod = 4; + break; + case 4: + if (channelBitmap & kAudioChannelBit_CenterSurround) acmod = 5; + else acmod = 6; + break; + case 5: + acmod = 7; + break; + default: + break; + } + + if (asbd->mSampleRate == 48000) fscod = 0; + else if (asbd->mSampleRate == 44100) fscod = 1; + else if (asbd->mSampleRate == 32000) fscod = 2; + else fscod = 3; + + NSMutableData *ac3Info = [[NSMutableData alloc] init]; + [ac3Info appendBytes:&fscod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsid length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&acmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&lfeon length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bit_rate_code length:sizeof(uint64_t)]; + + return [ac3Info autorelease]; + + } + else if (cookieSizeOut) + return [NSData dataWithBytes:magicCookie length:cookieSizeOut]; + } + } + return nil; +} + +- (void)demux:(id)sender +{ + BOOL success = YES; + OSStatus err = noErr; + + uint64_t currentDataLength = 0; + uint64_t totalDataLength = 0; + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + AVFDemuxHelper *demuxHelper=nil; + NSError *localError; + AVAssetReader *assetReader = [[AVAssetReader alloc] initWithAsset:_localAsset error:&localError]; + + success = (assetReader != nil); + if (success) { + for (MP42Track * track in _inputTracks) { + AVAssetReaderOutput *assetReaderOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:[_localAsset trackWithTrackID:track.sourceId] outputSettings:nil]; + if (! [assetReader canAddOutput: assetReaderOutput]) + NSLog(@"Unable to add the output to assetReader!"); + + [assetReader addOutput:assetReaderOutput]; + + track.muxer_helper->demuxer_context = [[AVFDemuxHelper alloc] init]; + demuxHelper = track.muxer_helper->demuxer_context; + demuxHelper->assetReaderOutput = assetReaderOutput; + + totalDataLength += [track dataLength]; + } + } + + success = [assetReader startReading]; + if (!success) + localError = [assetReader error]; + + for (MP42Track * track in _inputTracks) { + demuxHelper = track.muxer_helper->demuxer_context; + AVAssetReaderOutput *assetReaderOutput = demuxHelper->assetReaderOutput; + + while (!_cancelled) { + CMSampleBufferRef sampleBuffer = [assetReaderOutput copyNextSampleBuffer]; + if (sampleBuffer) { + CMItemCount samplesNum = CMSampleBufferGetNumSamples(sampleBuffer); + if (samplesNum == 1) { + // We have only a sample + CMTime duration = CMSampleBufferGetDuration(sampleBuffer); + CMTime decodeTimeStamp = CMSampleBufferGetDecodeTimeStamp(sampleBuffer); + CMTime presentationTimeStamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer); + CMTime presentationOutputTimeStamp = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer); + + CMBlockBufferRef buffer = CMSampleBufferGetDataBuffer(sampleBuffer); + size_t sampleSize = CMBlockBufferGetDataLength(buffer); + void *sampleData = malloc(sampleSize); + CMBlockBufferCopyDataBytes(buffer, 0, sampleSize, sampleData); + + // Read sample attachment, sync to mark the frame as sync, do not display to create a new edit list + BOOL sync = 1; + BOOL doNotDisplay = 0; + CFArrayRef attachmentsArray = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, NO); + if (attachmentsArray) { + for (NSDictionary *dict in (NSArray*)attachmentsArray) { + if ([dict valueForKey:(NSString*)kCMSampleAttachmentKey_NotSync]) + sync = 0; + if ([dict valueForKey:(NSString*)kCMSampleAttachmentKey_DoNotDisplay]) { + doNotDisplay = 1; + } + } + } + + if ((presentationTimeStamp.value + demuxHelper->correctionValue) != presentationOutputTimeStamp.value) { + if (!demuxHelper->discontinuity) + demuxHelper->discontinuity = (CMTimeRange *) malloc(sizeof(CMTimeRange) * 100); + + NSLog(@"We found a timestamp discontinuity"); + NSLog(@"Current presentationTimeStamp: %lld", presentationTimeStamp.value); + demuxHelper->correctionValue = -presentationTimeStamp.value + presentationOutputTimeStamp.value; + //demuxHelper->disTimeStamp = presentationOutputTimeStamp.value; + NSLog(@"Making an adjustment of %lld", -demuxHelper->correctionValue); + NSLog(@"Timestamp of discontinuity %lld", presentationOutputTimeStamp.value); + + demuxHelper->discontinuity[demuxHelper->discontinuityCount].start = presentationTimeStamp; + demuxHelper->discontinuity[demuxHelper->discontinuityCount].duration.value = -demuxHelper->correctionValue; //presentationTimeStamp.value; + demuxHelper->discontinuity[demuxHelper->discontinuityCount].duration.timescale = presentationTimeStamp.timescale; + + demuxHelper->discontinuityCount++; + demuxHelper->countFrames = YES; + } + if (demuxHelper->countFrames) { + demuxHelper->disTimeStamp += duration.value; + } + + if (presentationOutputTimeStamp.value >= demuxHelper->currentTime.value) { + demuxHelper->currentTime = presentationOutputTimeStamp; + if (demuxHelper->countFrames) { + demuxHelper->discontinuity[demuxHelper->discontinuityCount-1].duration.value -= demuxHelper->disTimeStamp; + NSLog(@"Corrected decode time stamp: %lld", demuxHelper->disTimeStamp); + } + demuxHelper->countFrames = NO; + } + + //NSLog(@"D: %lld, P: %lld, PO: %lld Display: %d", decodeTimeStamp.value, presentationTimeStamp.value, presentationOutputTimeStamp.value, doNotDisplay); + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = sampleData; + sample->size = sampleSize; + sample->duration = duration.value; + sample->offset = -decodeTimeStamp.value + presentationTimeStamp.value; + sample->timestamp = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer).value; + sample->isSync = sync; + sample->trackId = track.sourceId; + + [self enqueue:sample]; + [sample release]; + + currentDataLength += sampleSize; + } + else { + if (!CMSampleBufferDataIsReady(sampleBuffer)) + CMSampleBufferMakeDataReady(sampleBuffer); + + // A CMSampleBufferRef can contains an unknown number of samples, check how many needs to be divided to separated MP42SampleBuffers + // First get the array with the timings for each sample + CMItemCount timingArrayEntries = 0; + CMItemCount timingArrayEntriesNeededOut = 0; + err = CMSampleBufferGetSampleTimingInfoArray(sampleBuffer, timingArrayEntries, NULL, &timingArrayEntriesNeededOut); + if (err) + continue; + + CMSampleTimingInfo *timingArrayOut = malloc(sizeof(CMSampleTimingInfo) * timingArrayEntriesNeededOut); + timingArrayEntries = timingArrayEntriesNeededOut; + err = CMSampleBufferGetSampleTimingInfoArray(sampleBuffer, timingArrayEntries, timingArrayOut, &timingArrayEntriesNeededOut); + if (err) + continue; + + // Then the array with the size of each sample + CMItemCount sizeArrayEntries = 0; + CMItemCount sizeArrayEntriesNeededOut = 0; + err = CMSampleBufferGetSampleSizeArray(sampleBuffer, sizeArrayEntries, NULL, &sizeArrayEntriesNeededOut); + if (err) + continue; + + size_t *sizeArrayOut = malloc(sizeof(size_t) * sizeArrayEntriesNeededOut); + sizeArrayEntries = sizeArrayEntriesNeededOut; + err = CMSampleBufferGetSampleSizeArray(sampleBuffer, sizeArrayEntries, sizeArrayOut, &sizeArrayEntriesNeededOut); + if (err) + continue; + + // Get CMBlockBufferRef to extract the actual data later + CMBlockBufferRef buffer = CMSampleBufferGetDataBuffer(sampleBuffer); + size_t bufferSize = CMBlockBufferGetDataLength(buffer); + + int i = 0, pos = 0; + for (i = 0; i < samplesNum; i++) { + CMSampleTimingInfo sampleTimingInfo; + CMTime decodeTimeStamp = {0,0,0,0}; + CMTime presentationTimeStamp = {0,0,0,0}; + CMTime presentationOutputTimeStamp = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer); + + size_t sampleSize; + + // If the size of sample timing array is equal to 1, it means every sample has got the same timing + if (timingArrayEntries == 1) { + sampleTimingInfo = timingArrayOut[0]; + decodeTimeStamp = sampleTimingInfo.decodeTimeStamp; + decodeTimeStamp.value = decodeTimeStamp.value + ( sampleTimingInfo.duration.value * i); + + presentationTimeStamp = sampleTimingInfo.presentationTimeStamp; + presentationTimeStamp.value = presentationTimeStamp.value + ( sampleTimingInfo.duration.value * i); + + } + else { + sampleTimingInfo = timingArrayOut[i]; + decodeTimeStamp = sampleTimingInfo.decodeTimeStamp; + presentationTimeStamp = sampleTimingInfo.presentationTimeStamp; + } + + presentationOutputTimeStamp.value = presentationOutputTimeStamp.value + ( sampleTimingInfo.duration.value * i / ( (double) sampleTimingInfo.duration.timescale / presentationOutputTimeStamp.timescale)); + + // If the size of sample size array is equal to 1, it means every sample has got the same size + if (sizeArrayEntries == 1) + sampleSize = sizeArrayOut[0]; + else + sampleSize = sizeArrayOut[i]; + + if (!sampleSize) + continue; + + void *sampleData = malloc(sampleSize); + + if (pos < bufferSize) { + CMBlockBufferCopyDataBytes(buffer, pos, sampleSize, sampleData); + pos += sampleSize; + } + + BOOL sync = 1; + BOOL doNotDisplay = 0; + CFArrayRef attachmentsArray = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, NO); + if (attachmentsArray) { + for (NSDictionary *dict in (NSArray*)attachmentsArray) { + if ([dict valueForKey:(NSString*)kCMSampleAttachmentKey_NotSync]) + sync = 0; + if ([dict valueForKey:(NSString*)kCMSampleAttachmentKey_DoNotDisplay]) + doNotDisplay = 1; + } + } + + if ((presentationTimeStamp.value + demuxHelper->correctionValue) != presentationOutputTimeStamp.value) { + if (!demuxHelper->discontinuity) + demuxHelper->discontinuity = (CMTimeRange *) malloc(sizeof(CMTimeRange) * 100); + + NSLog(@"We found a timestamp discontinuity"); + NSLog(@"Current presentationTimeStamp: %lld", presentationTimeStamp.value); + demuxHelper->correctionValue = -presentationTimeStamp.value + presentationOutputTimeStamp.value; + //demuxHelper->disTimeStamp = presentationOutputTimeStamp.value; + NSLog(@"Making an adjustment of %lld", -demuxHelper->correctionValue); + NSLog(@"Timestamp of discontinuity %lld", presentationOutputTimeStamp.value); + + demuxHelper->discontinuity[demuxHelper->discontinuityCount].start = presentationTimeStamp; + demuxHelper->discontinuity[demuxHelper->discontinuityCount].duration.value = -demuxHelper->correctionValue; //presentationTimeStamp.value; + demuxHelper->discontinuity[demuxHelper->discontinuityCount].duration.timescale = presentationTimeStamp.timescale; + + demuxHelper->discontinuityCount++; + demuxHelper->countFrames = YES; + } + if (demuxHelper->countFrames) { + demuxHelper->disTimeStamp += sampleTimingInfo.duration.value; + } + + if (presentationOutputTimeStamp.value >= demuxHelper->currentTime.value) { + demuxHelper->currentTime = presentationOutputTimeStamp; + if (demuxHelper->countFrames) { + demuxHelper->discontinuity[demuxHelper->discontinuityCount-1].duration.value -= demuxHelper->disTimeStamp; + NSLog(@"Corrected decode time stamp: %lld", demuxHelper->disTimeStamp); + } + demuxHelper->countFrames = NO; + } + + //NSLog(@"D: %lld, P: %lld, PO: %lld", decodeTimeStamp.value, presentationTimeStamp.value, presentationOutputTimeStamp.value); + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = sampleData; + sample->size = sampleSize; + sample->duration = sampleTimingInfo.duration.value; + sample->offset = 0; //-sampleTimingInfo.decodeTimeStamp.value + sampleTimingInfo.presentationTimeStamp.value; + sample->timestamp = sampleTimingInfo.presentationTimeStamp.value; + sample->isSync = sync; + sample->trackId = track.sourceId; + + [self enqueue:sample]; + [sample release]; + + currentDataLength += sampleSize; + } + + if(timingArrayOut) + free(timingArrayOut); + if(sizeArrayOut) + free(sizeArrayOut); + } + CFRelease(sampleBuffer); + + _progress = (((CGFloat) currentDataLength / totalDataLength ) * 100); + + } + else { + AVAssetReaderStatus status = assetReader.status; + + if (status == AVAssetReaderStatusCompleted) { + NSLog(@"AVAssetReader: done"); + } + + break; + } + } + } + + [assetReader release]; + [self setDone:YES]; + [pool release]; +} + +- (void)startReading +{ + [super startReading]; + + if (!_demuxerThread && !_done) { + _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; + [_demuxerThread setName:@"AVFoundation Demuxer"]; + [_demuxerThread start]; + } +} + +- (BOOL)cleanUp:(MP4FileHandle) fileHandle +{ + uint32_t timescale = MP4GetTimeScale(fileHandle); + long i; + + for (MP42Track *track in _inputTracks) { + AVAssetTrack *assetTrack = [_localAsset trackWithTrackID:track.sourceId]; + MP42Track *inputTrack = [self inputTrackWithTrackID:track.sourceId]; + + MP4Duration trackDuration = 0; + MP4Timestamp editDuration; + + AVFDemuxHelper *demuxHelper = inputTrack.muxer_helper->demuxer_context; + + for (AVAssetTrackSegment *segment in assetTrack.segments) { + bool empty = NO; + CMTimeMapping timeMapping = segment.timeMapping; + CMTimeValue correction = 0; + + for (i = demuxHelper->discontinuityCount - 1; i >= 0; i--) { + CMTimeRange timeRange = demuxHelper->discontinuity[i]; + + if (timeMapping.source.start.value > timeRange.start.value) { + correction = timeRange.duration.value; + NSLog(@"Discontinuity --"); + NSLog(@"Presentation Time: %lld", timeRange.start.value); + NSLog(@"Timescale: %d", timeRange.start.timescale); + NSLog(@"Correction: %lld", timeRange.duration.value); + + break; + } + + } + + if (timeMapping.source.duration.flags & kCMTimeFlags_Indefinite || timeMapping.target.duration.flags & kCMTimeFlags_Indefinite) { + NSLog(@"Indefinite time mappings"); + } + else { + NSLog(@"Source --"); + NSLog(@"Start: %lld", timeMapping.source.start.value); + NSLog(@"Timescale: %d", timeMapping.source.start.timescale); + NSLog(@"Duration: %lld", timeMapping.source.duration.value); + NSLog(@"Timescale: %d", timeMapping.source.duration.timescale); + + NSLog(@"Target --"); + NSLog(@"Start %lld", timeMapping.target.start.value); + NSLog(@"Timescale: %d", timeMapping.target.start.timescale); + NSLog(@"Duration: %lld", timeMapping.target.duration.value); + NSLog(@"Timescale: %d", timeMapping.target.start.timescale); + + if (segment.empty) { + NSLog(@"Empty segment"); + empty = YES; + } + + editDuration = timeMapping.target.duration.value * ((double) timescale / timeMapping.target.duration.timescale); + + if (empty) + MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, -1, + editDuration, 0); + else + MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, timeMapping.source.start.value - correction, + editDuration, 0); + + trackDuration = trackDuration + editDuration; + + } + } + if (trackDuration) + MP4SetTrackIntegerProperty(fileHandle, track.Id, "tkhd.duration", trackDuration); + } + return YES; +} + +- (void) dealloc +{ + [_localAsset release]; + + [super dealloc]; +} + +@end + +#endif diff --git a/MP42/MP42AudioConverter.h b/MP42/MP42AudioConverter.h new file mode 100644 index 0000000..0c94009 --- /dev/null +++ b/MP42/MP42AudioConverter.h @@ -0,0 +1,91 @@ +// +// SBAudioConverter.h +// Subler +// +// Created by Damiano Galassi on 16/09/10. +// Copyright 2010 Damiano Galassi. All rights reserved. +// + +#import +#include "sfifo.h" +#include "downmix.h" +#import "MP42ConverterProtocol.h" + +#import +#import + +@class MP42SampleBuffer; +@class MP42Fifo; +@class MP42AudioTrack; + +extern NSString * const SBMonoMixdown; +extern NSString * const SBStereoMixdown; +extern NSString * const SBDolbyMixdown; +extern NSString * const SBDolbyPlIIMixdown; + +// a struct to hold info for the data proc +struct AudioFileIO +{ + AudioConverterRef converter; + AudioStreamBasicDescription inputFormat; + AudioStreamBasicDescription outputFormat; + + sfifo_t *fifo; + + SInt64 pos; + char * srcBuffer; + UInt32 srcBufferSize; + UInt32 srcSizePerPacket; + UInt32 numPacketsPerRead; + + AudioStreamBasicDescription srcFormat; + AudioStreamPacketDescription *pktDescs; + + MP42Fifo *inputSamplesBuffer; + + MP42SampleBuffer *sample; + int fileReaderDone; +} AudioFileIO; + +@interface MP42AudioConverter : NSObject { + NSThread *decoderThread; + NSThread *encoderThread; + + unsigned char *buffer; + int bufferSize; + sfifo_t fifo; + + BOOL readerDone; + BOOL encoderDone; + + int32_t _cancelled; + + Float64 sampleRate; + UInt32 inputChannelsCount; + UInt32 outputChannelCount; + NSUInteger downmixType; + NSUInteger layout; + hb_chan_map_t *ichanmap; + + MP42Fifo *_inputSamplesBuffer; + MP42Fifo *_outputSamplesBuffer; + + NSData * outputMagicCookie; + + struct AudioFileIO decoderData; + struct AudioFileIO encoderData; +} + +- (instancetype)initWithTrack:(MP42AudioTrack*)track andMixdownType:(NSString *)mixdownType error:(NSError **)outError; + +- (void)addSample:(MP42SampleBuffer *)sample; +- (MP42SampleBuffer *)copyEncodedSample; + +- (NSData *)magicCookie; + +- (void)cancel; +- (BOOL)encoderDone; + +- (void)setInputDone; + +@end diff --git a/MP42/MP42AudioConverter.m b/MP42/MP42AudioConverter.m new file mode 100644 index 0000000..b0db92c --- /dev/null +++ b/MP42/MP42AudioConverter.m @@ -0,0 +1,842 @@ +// +// SBAudioConverter.m +// Subler +// +// Created by Damiano Galassi on 16/09/10. +// Copyright 2010 Damiano Galassi. All rights reserved. +// + +#import "MP42AudioConverter.h" +#import "MP42Track.h" +#import "MP42AudioTrack.h" +#import "MP42FileImporter.h" +#import "MP42MediaFormat.h" +#import "MP42Fifo.h" +#import "MP42Utilities.h" + +#define FIFO_DURATION (0.5f) + +NSString * const SBMonoMixdown = @"SBMonoMixdown"; +NSString * const SBStereoMixdown = @"SBStereoMixdown"; +NSString * const SBDolbyMixdown = @"SBDolbyMixdown"; +NSString * const SBDolbyPlIIMixdown = @"SBDolbyPlIIMixdown"; + +@interface NSString (VersionStringCompare) +- (BOOL)isVersionStringOlderThan:(NSString *)older; +@end + +@implementation NSString (VersionStringCompare) +- (BOOL)isVersionStringOlderThan:(NSString *)older +{ + if([self compare:older] == NSOrderedAscending) + return TRUE; + if([self hasPrefix:older] && [self length] > [older length] && [self characterAtIndex:[older length]] == 'b') + //1.0b1 < 1.0, so check for it. + return TRUE; + return FALSE; +} +@end + +#define ComponentNameKey @"Name" +#define ComponentArchiveNameKey @"ArchiveName" +#define ComponentTypeKey @"Type" + +#define BundleVersionKey @"CFBundleVersion" +#define BundleIdentifierKey @"CFBundleIdentifier" + +typedef enum +{ + InstallStatusInstalledInWrongLocation = 0, + InstallStatusNotInstalled = 1, + InstallStatusOutdatedWithAnotherInWrongLocation = 2, + InstallStatusOutdated = 3, + InstallStatusInstalledInBothLocations = 4, + InstallStatusInstalled = 5 +} InstallStatus; + +typedef enum +{ + ComponentTypeQuickTime, + ComponentTypeCoreAudio, + ComponentTypeFramework +} ComponentType; + +InstallStatus currentInstallStatus(InstallStatus status) +{ + return (status | 1); +} + +InstallStatus setWrongLocationInstalled(InstallStatus status) +{ + return (status & ~1); +} + +@implementation MP42AudioConverter + +- (NSString *)installationBasePath:(BOOL)userInstallation +{ + if(userInstallation) + return NSHomeDirectory(); + return @"/"; +} + +- (NSString *)quickTimeComponentDir:(BOOL)userInstallation +{ + return [[self installationBasePath:userInstallation] stringByAppendingPathComponent:@"Library/QuickTime"]; +} + +- (NSString *)coreAudioComponentDir:(BOOL)userInstallation +{ + return [[self installationBasePath:userInstallation] stringByAppendingPathComponent:@"Library/Audio/Plug-Ins/Components"]; +} + +- (NSString *)frameworkComponentDir:(BOOL)userInstallation +{ + return [[self installationBasePath:userInstallation] stringByAppendingPathComponent:@"Library/Frameworks"]; +} + +- (NSString *)basePathForType:(ComponentType)type user:(BOOL)userInstallation +{ + NSString *path = nil; + + switch(type) + { + case ComponentTypeCoreAudio: + path = [self coreAudioComponentDir:userInstallation]; + break; + case ComponentTypeQuickTime: + path = [self quickTimeComponentDir:userInstallation]; + break; + case ComponentTypeFramework: + path = [self frameworkComponentDir:userInstallation]; + break; + } + return path; +} + +- (InstallStatus)installStatusForComponent:(NSString *)component type:(ComponentType)type version:(NSString*) version; +{ + NSString *path = nil; + InstallStatus ret = InstallStatusNotInstalled; + + path = [[self basePathForType:type user:YES] stringByAppendingPathComponent:component]; + + NSDictionary *infoDict = [NSDictionary dictionaryWithContentsOfFile:[path stringByAppendingPathComponent:@"Contents/Info.plist"]]; + if(infoDict != nil) + { + NSString *currentVersion = [infoDict objectForKey:BundleVersionKey];; + if([currentVersion isVersionStringOlderThan:version]) + ret = InstallStatusOutdated; + else + ret = InstallStatusInstalled; + } + + /* Check other installation type */ + path = [[self basePathForType:type user:NO] stringByAppendingPathComponent:component]; + + infoDict = [NSDictionary dictionaryWithContentsOfFile:[path stringByAppendingPathComponent:@"Contents/Info.plist"]]; + if(infoDict != nil) + { + NSString *currentVersion = [infoDict objectForKey:BundleVersionKey];; + if([currentVersion isVersionStringOlderThan:version]) + ret = InstallStatusOutdated; + else + ret = InstallStatusInstalled; + } + + return (ret); +} + +OSStatus EncoderDataProc(AudioConverterRef inAudioConverter, + UInt32* ioNumberDataPackets, + AudioBufferList* ioData, + AudioStreamPacketDescription** outDataPacketDescription, + void* inUserData) +{ + struct AudioFileIO* afio = (struct AudioFileIO*)inUserData; + + // figure out how much to read + if (*ioNumberDataPackets > afio->numPacketsPerRead) *ioNumberDataPackets = afio->numPacketsPerRead; + + // read from the fifo + UInt32 outNumBytes; + unsigned int wanted = MIN(*ioNumberDataPackets * afio->srcSizePerPacket, sfifo_used(afio->fifo)); + + outNumBytes = sfifo_read(afio->fifo, afio->srcBuffer, wanted); + OSStatus err = noErr; + if (outNumBytes < wanted) { + *ioNumberDataPackets = 0; + printf ("Input Proc Read error: %d (%4.4s)\n", (int)err, (char*)&err); + return err; + } + + if (*ioNumberDataPackets == 0) + printf ("End\n"); + + // put the data pointer into the buffer list + + ioData->mBuffers[0].mData = afio->srcBuffer; + ioData->mBuffers[0].mDataByteSize = outNumBytes; + ioData->mBuffers[0].mNumberChannels = afio->srcFormat.mChannelsPerFrame; + + *ioNumberDataPackets = ioData->mBuffers[0].mDataByteSize / afio->srcSizePerPacket; + + afio->pos += *ioNumberDataPackets; + + if (outDataPacketDescription) { + if (afio->pktDescs) + *outDataPacketDescription = afio->pktDescs; + else + *outDataPacketDescription = NULL; + } + + return err; +} + +- (void)EncoderThreadMainRoutine:(id)sender +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + encoderDone = NO; + OSStatus err; + + // set up aac converter + AudioConverterRef converterEnc; + AudioStreamBasicDescription inputFormat, encoderFormat; + + bzero( &inputFormat, sizeof( AudioStreamBasicDescription ) ); + inputFormat.mSampleRate = sampleRate; + inputFormat.mFormatID = kAudioFormatLinearPCM ; + inputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat | kAudioFormatFlagsNativeEndian; + inputFormat.mBytesPerPacket = 4 * outputChannelCount; + inputFormat.mFramesPerPacket = 1; + inputFormat.mBytesPerFrame = inputFormat.mBytesPerPacket * inputFormat.mFramesPerPacket; + inputFormat.mChannelsPerFrame = outputChannelCount; + inputFormat.mBitsPerChannel = 32; + + bzero( &encoderFormat, sizeof( AudioStreamBasicDescription ) ); + encoderFormat.mFormatID = kAudioFormatMPEG4AAC; + encoderFormat.mSampleRate = ( Float64 ) inputFormat.mSampleRate; + encoderFormat.mChannelsPerFrame = inputFormat.mChannelsPerFrame; + + err = AudioConverterNew( &inputFormat, &encoderFormat, &converterEnc ); + if (err) + NSLog(@"Boom encoder converter init failed"); + + UInt32 tmp, tmpsiz = sizeof( tmp ); + + // set encoder quality to maximum + tmp = kAudioConverterQuality_Max; + AudioConverterSetProperty( converterEnc, kAudioConverterCodecQuality, + sizeof( tmp ), &tmp ); + + // set encoder bitrate control mode to constrained variable + tmp = kAudioCodecBitRateControlMode_VariableConstrained; + AudioConverterSetProperty( converterEnc, kAudioCodecPropertyBitRateControlMode, + sizeof( tmp ), &tmp ); + + // set bitrate + UInt32 bitrate = (UInt32)[[[NSUserDefaults standardUserDefaults] valueForKey:@"SBAudioBitrate"] integerValue]; + if (!bitrate) bitrate = 80; + + // get available bitrates + AudioValueRange *bitrates; + ssize_t bitrateCounts; + err = AudioConverterGetPropertyInfo( converterEnc, kAudioConverterApplicableEncodeBitRates, + &tmpsiz, NULL); + if (err) { + NSLog(@"err kAudioConverterApplicableEncodeBitRates From AudioConverter"); + } + bitrates = malloc( tmpsiz ); + err = AudioConverterGetProperty( converterEnc, kAudioConverterApplicableEncodeBitRates, + &tmpsiz, bitrates); + if (err) { + NSLog(@"err kAudioConverterApplicableEncodeBitRates From AudioConverter"); + } + bitrateCounts = tmpsiz / sizeof( AudioValueRange ); + + // set bitrate + tmp = bitrate * outputChannelCount * 1000; + if( tmp < bitrates[0].mMinimum ) + tmp = bitrates[0].mMinimum; + if( tmp > bitrates[bitrateCounts-1].mMinimum ) + tmp = bitrates[bitrateCounts-1].mMinimum; + free( bitrates ); + + AudioConverterSetProperty( converterEnc, kAudioConverterEncodeBitRate, + sizeof( tmp ), &tmp ); + + // get real input + tmpsiz = sizeof( inputFormat ); + AudioConverterGetProperty( converterEnc, + kAudioConverterCurrentInputStreamDescription, + &tmpsiz, &inputFormat ); + + // get real output + tmpsiz = sizeof( encoderFormat ); + AudioConverterGetProperty( converterEnc, + kAudioConverterCurrentOutputStreamDescription, + &tmpsiz, &encoderFormat ); + + // set up buffers and data proc info struct + encoderData.srcBufferSize = 32768; + encoderData.srcBuffer = (char *)malloc( encoderData.srcBufferSize ); + encoderData.pos = 0; + encoderData.srcFormat = inputFormat; + encoderData.srcSizePerPacket = inputFormat.mBytesPerPacket; + encoderData.numPacketsPerRead = encoderData.srcBufferSize / encoderData.srcSizePerPacket; + encoderData.pktDescs = NULL; + encoderData.fifo = &fifo; + + // set up our output buffers + + int outputSizePerPacket = encoderFormat.mBytesPerPacket; // this will be non-zero if the format is CBR + UInt32 size = sizeof(outputSizePerPacket); + err = AudioConverterGetProperty(converterEnc, kAudioConverterPropertyMaximumOutputPacketSize, + &size, &outputSizePerPacket); + if (err) + NSLog(@"Boom kAudioConverterPropertyMaximumOutputPacketSize"); + + UInt32 theOutputBufSize = outputSizePerPacket; + char* outputBuffer = (char*)malloc(theOutputBufSize); + + // grab the cookie from the converter and write it to the file + UInt32 cookieSize = 0; + err = AudioConverterGetPropertyInfo(converterEnc, kAudioConverterCompressionMagicCookie, &cookieSize, NULL); + // if there is an error here, then the format doesn't have a cookie, so on we go + if (!err && cookieSize) { + char* cookie = (char *) malloc(cookieSize); + UInt8* cookieBuffer; + int size; + + err = AudioConverterGetProperty(converterEnc, kAudioConverterCompressionMagicCookie, &cookieSize, cookie); + if (err) { + NSLog(@"err Get Cookie From AudioConverter"); + } + ReadESDSDescExt(cookie, &cookieBuffer, &size, 1); + outputMagicCookie = [[NSData dataWithBytes:cookieBuffer length:size] retain]; + + free(cookieBuffer); + free(cookie); + } + + // loop to convert data + SInt64 outputPos = 0; + + while (1) { + AudioStreamPacketDescription odesc = {0}; + + // set up output buffer list + AudioBufferList fillBufList; + fillBufList.mNumberBuffers = 1; + fillBufList.mBuffers[0].mNumberChannels = inputFormat.mChannelsPerFrame; + fillBufList.mBuffers[0].mDataByteSize = theOutputBufSize; + fillBufList.mBuffers[0].mData = outputBuffer; + + while ((sfifo_used(&fifo) < (inputFormat.mBytesPerPacket * encoderFormat.mFramesPerPacket * 4)) && !readerDone) + usleep(500); + + // convert data + UInt32 ioOutputDataPackets = 1; + err = AudioConverterFillComplexBuffer(converterEnc, EncoderDataProc, &encoderData, &ioOutputDataPackets, + &fillBufList, &odesc); + if (err) + NSLog(@"Error converterEnc %ld", (long)err); + if (ioOutputDataPackets == 0) { + // this is the EOF conditon + break; + } + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = malloc(fillBufList.mBuffers[0].mDataByteSize); + memcpy(sample->data, outputBuffer, fillBufList.mBuffers[0].mDataByteSize); + + sample->size = fillBufList.mBuffers[0].mDataByteSize; + sample->duration = 1024; + sample->offset = 0; + sample->timestamp = outputPos; + sample->isSync = YES; + + while ([_outputSamplesBuffer isFull] && !_cancelled) + usleep(500); + + [_outputSamplesBuffer enqueue:sample]; + [sample release]; + + outputPos += ioOutputDataPackets; + } + + free(outputBuffer); + + AudioConverterDispose(converterEnc); + + [pool release]; + + encoderDone = YES; + + return; +} + +// decoder input data proc callback + +OSStatus DecoderDataProc(AudioConverterRef inAudioConverter, + UInt32* ioNumberDataPackets, + AudioBufferList* ioData, + AudioStreamPacketDescription** outDataPacketDescription, + void* inUserData) +{ + OSStatus err = noErr; + struct AudioFileIO * afio = inUserData; + + if (afio->sample) + [afio->sample release]; + + // figure out how much to read + if (*ioNumberDataPackets > afio->numPacketsPerRead) *ioNumberDataPackets = afio->numPacketsPerRead; + + // read from the buffer + while (![afio->inputSamplesBuffer count] && !afio->fileReaderDone) + usleep(250); + + if (![afio->inputSamplesBuffer count] && afio->fileReaderDone) { + *ioNumberDataPackets = 0; + return err; + } + else { + afio->sample = [afio->inputSamplesBuffer deque]; + } + + // advance input file packet position + afio->pos += *ioNumberDataPackets; + + // put the data pointer into the buffer list + ioData->mBuffers[0].mData = afio->sample->data; + ioData->mBuffers[0].mDataByteSize = afio->sample->size; + ioData->mBuffers[0].mNumberChannels = afio->srcFormat.mChannelsPerFrame; + + if (outDataPacketDescription) { + if (afio->pktDescs) { + afio->pktDescs->mStartOffset = 0; + afio->pktDescs->mVariableFramesInPacket = *ioNumberDataPackets; + afio->pktDescs->mDataByteSize = afio->sample->size; + *outDataPacketDescription = afio->pktDescs; + } + else + *outDataPacketDescription = NULL; + } + + return err; +} + +- (void)DecoderThreadMainRoutine:(id)sender +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + OSStatus err; + + // set up buffers and data proc info struct + decoderData.srcBufferSize = 32768; + decoderData.srcBuffer = (char *)malloc( decoderData.srcBufferSize ); + decoderData.pos = 0; + decoderData.srcFormat = decoderData.inputFormat; + decoderData.numPacketsPerRead = 1; + decoderData.pktDescs = (AudioStreamPacketDescription*)malloc(decoderData.numPacketsPerRead); + decoderData.inputSamplesBuffer = _inputSamplesBuffer; + + // set up our output buffers + AudioStreamPacketDescription* outputPktDescs = NULL; + int outputSizePerPacket = decoderData.outputFormat.mBytesPerPacket; // this will be non-zero if the format is CBR + UInt32 theOutputBufSize = 32768; + char* outputBuffer = (char*)malloc(theOutputBufSize); + + UInt32 numOutputPackets = theOutputBufSize / outputSizePerPacket; + + // Launch the encoder thread + encoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(EncoderThreadMainRoutine:) object:self]; + [encoderThread setName:@"AAC Encoder"]; + [encoderThread start]; + + // Set up our fifo + int ringbuffer_len = sampleRate * FIFO_DURATION * 4 * 23; + sfifo_init(&fifo, ringbuffer_len ); + bufferSize = ringbuffer_len >> 1; + buffer = (unsigned char *)malloc(bufferSize); + + decoderData.fifo = &fifo; + + // Check if we need to do any downmix + hb_downmix_t *downmix = NULL; + hb_sample_t *downmix_buffer = NULL; + + if (downmixType && inputChannelsCount == 6) { + downmix = hb_downmix_init(HB_INPUT_CH_LAYOUT_3F2R | HB_INPUT_CH_LAYOUT_HAS_LFE, + downmixType); + } + else if (downmixType && inputChannelsCount == 5) { + downmix = hb_downmix_init(HB_INPUT_CH_LAYOUT_3F2R, + downmixType); + } + else if (downmixType && inputChannelsCount == 4) { + downmix = hb_downmix_init(HB_INPUT_CH_LAYOUT_3F1R, + downmixType); + } + else if (downmixType && inputChannelsCount == 3) { + downmix = hb_downmix_init(HB_INPUT_CH_LAYOUT_STEREO | HB_INPUT_CH_LAYOUT_HAS_LFE, + downmixType); + } + else if (downmixType && inputChannelsCount == 2) { + downmix = hb_downmix_init(HB_INPUT_CH_LAYOUT_STEREO, + downmixType); + } + + // loop to convert data + while (1) { + // set up output buffer list + AudioBufferList fillBufList; + fillBufList.mNumberBuffers = 1; + fillBufList.mBuffers[0].mNumberChannels = decoderData.inputFormat.mChannelsPerFrame; + fillBufList.mBuffers[0].mDataByteSize = theOutputBufSize; + fillBufList.mBuffers[0].mData = outputBuffer; + + // convert data + UInt32 ioOutputDataPackets = numOutputPackets; + err = AudioConverterFillComplexBuffer(decoderData.converter, DecoderDataProc, &decoderData, &ioOutputDataPackets, + &fillBufList, outputPktDescs); + if (err) + NSLog(@"Error converterDec %ld", (long)err); + if (ioOutputDataPackets == 0) { + // this is the EOF conditon + break; + } + + + if( ichanmap != &hb_qt_chan_map ) { + hb_layout_remap( ichanmap, &hb_qt_chan_map, layout, + (float*)outputBuffer, + ioOutputDataPackets ); + } + // Dowmnix the audio if needed + if (downmix) { + size_t samplesBufferSize = ioOutputDataPackets * outputChannelCount * sizeof(float); + downmix_buffer = (float *)outputBuffer; + + hb_sample_t *samples = (hb_sample_t *)malloc(samplesBufferSize); + hb_downmix(downmix, samples, downmix_buffer, ioOutputDataPackets); + + while (sfifo_space(&fifo) < (samplesBufferSize)) + usleep(5000); + + sfifo_write(&fifo, samples, samplesBufferSize); + free(samples); + } + else { + UInt32 inNumBytes = fillBufList.mBuffers[0].mDataByteSize; + + while (sfifo_space(&fifo) < inNumBytes) + usleep(5000); + + sfifo_write(&fifo, outputBuffer, inNumBytes); + } + } + readerDone = YES; + + free(outputBuffer); + + if (downmix) + hb_downmix_close(&downmix); + + AudioConverterDispose(decoderData.converter); + + [pool drain]; + return; +} + +- (BOOL)errorMessageForFormat:(NSString *)format error:(NSError **)outError +{ + // Check if perian is installed + InstallStatus installStatus = [self installStatusForComponent:@"Perian.component" type:ComponentTypeQuickTime version:@"1.2"]; + + if(currentInstallStatus(installStatus) == InstallStatusNotInstalled) { + if (outError) + *outError = MP42Error(@"Perian is not installed.", + @"Perian is necessary for audio conversion in Subler. You can download it from http://perian.org/", + 130); + + return YES; + } + + // Check if xiphqt is installed + if ([format isEqualToString:MP42AudioFormatFLAC]) { + InstallStatus installStatus = [self installStatusForComponent:@"XiphQT.component" type:ComponentTypeQuickTime version:@"0.1.9"]; + + if(currentInstallStatus(installStatus) == InstallStatusNotInstalled) { + installStatus = [self installStatusForComponent:@"XiphQT (decoders).component" type:ComponentTypeQuickTime version:@"0.1.9"]; + + if(currentInstallStatus(installStatus) == InstallStatusNotInstalled) { + if (outError) + *outError = MP42Error(@"XiphQT is not installed.", + @"XiphQT is necessary for Flac audio conversion in Subler. You can download it from http://xiph.org/quicktime/", + 130); + + return YES; + } + } + } + + if (outError) + *outError = MP42Error(@"Unknown Error.", + @"Something went wrong in the audio converter", + 130); + + return YES; +} + +- (instancetype)initWithTrack:(MP42AudioTrack *)track andMixdownType:(NSString *) mixdownType error:(NSError **)outError +{ + if ((self = [super init])) { + OSStatus err; + + // Set the right mixdown to use + sampleRate = [track.muxer_helper->importer timescaleForTrack:track]; + inputChannelsCount = [track sourceChannels]; + outputChannelCount = [track channels]; + + if (outputChannelCount > inputChannelsCount) + outputChannelCount = inputChannelsCount; + + if ([mixdownType isEqualToString:SBMonoMixdown] && inputChannelsCount > 1) { + downmixType = HB_AMIXDOWN_MONO; + outputChannelCount = 1; + } + else if ([mixdownType isEqualToString:SBStereoMixdown] && inputChannelsCount > 2) { + downmixType = HB_AMIXDOWN_STEREO; + outputChannelCount = 2; + } + else if ([mixdownType isEqualToString:SBDolbyMixdown] && inputChannelsCount > 2) { + downmixType = HB_AMIXDOWN_DOLBY; + outputChannelCount = 2; + } + else if ([mixdownType isEqualToString:SBDolbyPlIIMixdown] && inputChannelsCount > 2) { + downmixType = HB_AMIXDOWN_DOLBYPLII; + outputChannelCount = 2; + } + + if (([track.sourceFormat isEqualToString:@"True HD"] || [track.sourceFormat isEqualToString:MP42AudioFormatAC3]) && inputChannelsCount == 6 ) { + ichanmap = &hb_smpte_chan_map; + layout = HB_INPUT_CH_LAYOUT_3F2R | HB_INPUT_CH_LAYOUT_HAS_LFE; + } + else { + ichanmap = &hb_qt_chan_map; + } + + _outputSamplesBuffer = [[MP42Fifo alloc] init]; + _inputSamplesBuffer = [[MP42Fifo alloc] init]; + + // Decoder initialization + CFDataRef magicCookie = NULL; + NSData * srcMagicCookie = [track.muxer_helper->importer magicCookieForTrack:track]; + AudioStreamBasicDescription inputFormat, outputFormat; + + bzero( &inputFormat, sizeof( AudioStreamBasicDescription ) ); + inputFormat.mSampleRate = sampleRate; + inputFormat.mChannelsPerFrame = track.sourceChannels; + + if (track.sourceFormat) { + if ([track.sourceFormat isEqualToString:MP42AudioFormatAAC]) { + inputFormat.mFormatID = kAudioFormatMPEG4AAC; + + size_t cookieSize; + uint8_t * cookie = CreateEsdsFromSetupData((uint8_t *)[srcMagicCookie bytes], [srcMagicCookie length], &cookieSize, 1, true, false); + magicCookie = (CFDataRef) [[NSData dataWithBytes:cookie length:cookieSize] retain]; + } + else if ([track.sourceFormat isEqualToString:MP42AudioFormatALAC]) { + inputFormat.mFormatID = kAudioFormatAppleLossless; + + magicCookie = (CFDataRef) [srcMagicCookie retain]; + } + else if ([track.sourceFormat isEqualToString:MP42AudioFormatVorbis]) { + inputFormat.mFormatID = 'XiVs'; + + magicCookie = createDescExt_XiphVorbis([srcMagicCookie length], [srcMagicCookie bytes]); + } + else if ([track.sourceFormat isEqualToString:MP42AudioFormatFLAC]) { + inputFormat.mFormatID = 'XiFL'; + + magicCookie = createDescExt_XiphFLAC([srcMagicCookie length], [srcMagicCookie bytes]); + } + else if ([track.sourceFormat isEqualToString:MP42AudioFormatAC3]) { + inputFormat.mFormatID = kAudioFormatAC3; + inputFormat.mFramesPerPacket = 1536; + } + else if ([track.sourceFormat isEqualToString:MP42AudioFormatDTS]) { + inputFormat.mFormatID = 'DTS '; + } + else if ([track.sourceFormat isEqualToString:MP42AudioFormatMP3]) { + inputFormat.mFormatID = kAudioFormatMPEGLayer3; + inputFormat.mFramesPerPacket = 1152; + } + else if ([track.sourceFormat isEqualToString:@"True HD"]) { + inputFormat.mFormatID = 'trhd'; + } + else if ([track.sourceFormat isEqualToString:MP42AudioFormatPCM]) { + AudioStreamBasicDescription temp = [track.muxer_helper->importer audioDescriptionForTrack:track]; + if (temp.mFormatID) + inputFormat = temp; + else + inputFormat.mFormatID = kAudioFormatLinearPCM; + } + } + + bzero( &outputFormat, sizeof( AudioStreamBasicDescription ) ); + outputFormat.mSampleRate = sampleRate; + outputFormat.mFormatID = kAudioFormatLinearPCM ; + outputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; + outputFormat.mBytesPerPacket = 4 * track.sourceChannels; + outputFormat.mFramesPerPacket = 1; + outputFormat.mBytesPerFrame = outputFormat.mBytesPerPacket * outputFormat.mFramesPerPacket; + outputFormat.mChannelsPerFrame = track.sourceChannels; + outputFormat.mBitsPerChannel = 32; + + // initialize the decoder + err = AudioConverterNew( &inputFormat, &outputFormat, &decoderData.converter ); + if ( err != noErr) { + if (outError) + if (![self errorMessageForFormat:track.sourceFormat error:outError]) { + *outError = MP42Error(@"Audio Converter Error.", + @"The Audio Converter can not be initialized", + 130); + } + if (magicCookie) + CFRelease(magicCookie); + [self release]; + return nil; + } + + // set the decoder magic cookie + if (magicCookie) { + err = AudioConverterSetProperty(decoderData.converter, kAudioConverterDecompressionMagicCookie, + CFDataGetLength(magicCookie) , CFDataGetBytePtr(magicCookie) ); + if( err != noErr) + NSLog(@"Boom Magic Cookie %ld",(long)err); + CFRelease(magicCookie); + } + + // Try to set the input channel layout + /*UInt32 propertySize = 0; + AudioChannelLayout * layout = NULL; + err = AudioConverterGetPropertyInfo(decoderData.converter, kAudioConverterInputChannelLayout, &propertySize, NULL); + + if (err == noErr && propertySize > 0) { + layout = malloc(sizeof(propertySize)); + err = AudioConverterGetProperty(decoderData.converter, kAudioConverterInputChannelLayout, &propertySize, layout); + if (err) { + NSLog(@"Unable to read the channel layout %ld",(long)err); + } + if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_MPEG_5_1_D && inputChannelsCount > 2) { + AudioChannelLayout * newLayout = malloc(sizeof(AudioChannelLayout)); + bzero( newLayout, sizeof( AudioChannelLayout ) ); + newLayout->mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_5_1_D; + err = AudioConverterSetProperty(decoderData.converter, kAudioConverterInputChannelLayout, sizeof(AudioChannelLayout), newLayout); + if(err) + NSLog(@"Unable to set the new channel layout %ld",(long)err); + free(newLayout); + } + free(layout); + }*/ + + /*if (([track.sourceFormat isEqualToString:@"True HD"] || [track.sourceFormat isEqualToString:MP42AudioFormatAC3]) && inputChannelsCount == 6 ) { + SInt32 channelMap[6] = { 2, 0, 1, 4, 5, 3 }; + AudioConverterSetProperty( decoderData.converter, kAudioConverterChannelMap, + sizeof( channelMap ), channelMap ); + }*/ + + // Read the complete inputStreamDescription from the audio converter. + UInt32 size = sizeof(inputFormat); + err = AudioConverterGetProperty( decoderData.converter, kAudioConverterCurrentInputStreamDescription, + &size, &inputFormat); + if( err != noErr) + NSLog(@"Boom kAudioConverterCurrentInputStreamDescription %ld",(long)err); + + // Read the complete outputStreamDescription from the audio converter. + size = sizeof(outputFormat); + err = AudioConverterGetProperty(decoderData.converter, kAudioConverterCurrentOutputStreamDescription, + &size, &outputFormat); + if( err != noErr) + NSLog(@"Boom kAudioConverterCurrentOutputStreamDescription %ld",(long)err); + + decoderData.inputFormat = inputFormat; + decoderData.outputFormat = outputFormat; + + // Launch the decoder thread. + decoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(DecoderThreadMainRoutine:) object:self]; + [decoderThread setName:@"Audio Decoder"]; + [decoderThread start]; + } + + return self; +} + +- (void)addSample:(MP42SampleBuffer *)sample +{ + [_inputSamplesBuffer enqueue:sample]; +} + +- (MP42SampleBuffer *)copyEncodedSample +{ + if (![_outputSamplesBuffer count]) + return nil; + + return [_outputSamplesBuffer deque]; +} + +- (void)setInputDone +{ + decoderData.fileReaderDone = YES; + encoderData.fileReaderDone = YES; +} + +- (void)cancel +{ + OSAtomicIncrement32(&_cancelled); + + decoderData.fileReaderDone = YES; + encoderData.fileReaderDone = YES; + + [_inputSamplesBuffer cancel]; + [_outputSamplesBuffer cancel]; + + while (!(readerDone && encoderDone)) + usleep(500); +} + +- (BOOL)encoderDone +{ + return encoderDone && [_outputSamplesBuffer isEmpty]; +} + +- (NSData *)magicCookie +{ + return [[outputMagicCookie retain] autorelease]; +} + +- (void)dealloc +{ + sfifo_close(&fifo); + + free(decoderData.srcBuffer); + free(decoderData.pktDescs); + + free(encoderData.srcBuffer); + free(encoderData.pktDescs); + + [outputMagicCookie release]; + + [decoderThread release]; + [encoderThread release]; + + [_outputSamplesBuffer release]; + [_inputSamplesBuffer release]; + + [super dealloc]; +} + +@end diff --git a/MP42/MP42AudioTrack.h b/MP42/MP42AudioTrack.h new file mode 100644 index 0000000..29cb510 --- /dev/null +++ b/MP42/MP42AudioTrack.h @@ -0,0 +1,40 @@ +// +// MP42SubtitleTrack.h +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import +#import "MP42Track.h" + +@interface MP42AudioTrack : MP42Track { + float _volume; + UInt32 _channels; + UInt32 _sourceChannels; + UInt32 _channelLayoutTag; + + MP42TrackId _fallbackTrackId; + MP42TrackId _followsTrackId; + + MP42Track *_fallbackTrack; + MP42Track *_followsTrack; + + NSString *_mixdownType; +} + +@property(nonatomic, readwrite) float volume; +@property(nonatomic, readwrite) UInt32 channels; +@property(nonatomic, readwrite) UInt32 sourceChannels; +@property(nonatomic, readwrite) UInt32 channelLayoutTag; + +@property(nonatomic, readonly) MP42TrackId fallbackTrackId; +@property(nonatomic, readonly) MP42TrackId followsTrackId; + +@property(nonatomic, readwrite, assign) MP42Track *fallbackTrack; +@property(nonatomic, readwrite, assign) MP42Track *followsTrack; + +@property(nonatomic, readwrite, retain) NSString *mixdownType; + +@end diff --git a/MP42/MP42AudioTrack.m b/MP42/MP42AudioTrack.m new file mode 100644 index 0000000..60307d8 --- /dev/null +++ b/MP42/MP42AudioTrack.m @@ -0,0 +1,258 @@ +// +// MP42SubtitleTrack.m +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import "MP42AudioTrack.h" +#import "MP42Utilities.h" +#import "MP42MediaFormat.h" + +extern u_int8_t MP4AV_AacConfigGetChannels(u_int8_t* pConfig); + +@implementation MP42AudioTrack + +- (instancetype)initWithSourceURL:(NSURL *)URL trackID:(NSInteger)trackID fileHandle:(MP4FileHandle)fileHandle +{ + if ((self = [super initWithSourceURL:URL trackID:trackID fileHandle:fileHandle])) { + MP4GetTrackFloatProperty(fileHandle, _Id, "tkhd.volume", &_volume); + _mediaType = MP42MediaTypeAudio; + + u_int8_t audioType = + MP4GetTrackEsdsObjectTypeId(fileHandle, _Id); + + if (audioType != MP4_INVALID_AUDIO_TYPE) { + if (MP4_IS_AAC_AUDIO_TYPE(audioType)) { + u_int8_t* pAacConfig = NULL; + u_int32_t aacConfigLength; + + if (MP4GetTrackESConfiguration(fileHandle, + _Id, + &pAacConfig, + &aacConfigLength) == true) + if (pAacConfig != NULL || aacConfigLength >= 2) { + _channels = MP4AV_AacConfigGetChannels(pAacConfig); + free(pAacConfig); + } + } else if ((audioType == MP4_PCM16_LITTLE_ENDIAN_AUDIO_TYPE) || + (audioType == MP4_PCM16_BIG_ENDIAN_AUDIO_TYPE)) { + u_int32_t samplesPerFrame = + MP4GetSampleSize(fileHandle, _Id, 1) / 2; + + MP4Duration frameDuration = + MP4GetSampleDuration(fileHandle, _Id, 1); + + if (frameDuration != 0) { + // assumes track time scale == sampling rate + _channels = samplesPerFrame / frameDuration; + } + } + } + if (audioType == 0xA9) { + uint64_t channels_count = 0; + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.mp4a.channels", &channels_count); + _channels = channels_count; + } + else if (MP4HaveTrackAtom(fileHandle, _Id, "mdia.minf.stbl.stsd.ac-3.dac3")) { + uint64_t acmod, lfeon; + + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.ac-3.dac3.acmod", &acmod); + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.ac-3.dac3.lfeon", &lfeon); + + readAC3Config(acmod, lfeon, &_channels, &_channelLayoutTag); + } + else if (MP4HaveTrackAtom(fileHandle, _Id, "mdia.minf.stbl.stsd.alac")) { + uint64_t channels_count = 0; + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.alac.channels", &channels_count); + _channels = channels_count; + } + + if (MP4HaveTrackAtom(fileHandle, _Id, "tref.fall")) { + uint64_t fallbackId = 0; + MP4GetTrackIntegerProperty(fileHandle, _Id, "tref.fall.entries.trackId", &fallbackId); + _fallbackTrackId = (MP4TrackId) fallbackId; + } + + if (MP4HaveTrackAtom(fileHandle, _Id, "tref.folw")) { + uint64_t followsId = 0; + MP4GetTrackIntegerProperty(fileHandle, _Id, "tref.folw.entries.trackId", &followsId); + _followsTrackId = (MP4TrackId) followsId; + } + + } + + return self; +} + +- (instancetype)init +{ + if ((self = [super init])) + { + _name = [self defaultName]; + _language = @"Unknown"; + _volume = 1; + _mixdownType = SBDolbyPlIIMixdown; + _mediaType = MP42MediaTypeAudio; + } + + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone +{ + MP42AudioTrack *copy = [super copyWithZone:zone]; + + if (copy) { + copy->_volume = _volume; + copy->_channels = _channels; + copy->_channelLayoutTag = _channelLayoutTag; + + copy->_fallbackTrackId = _fallbackTrackId; + copy->_followsTrackId = _followsTrackId; + + copy->_mixdownType = [_mixdownType retain]; + } + + return copy; +} + +- (BOOL)writeToFile:(MP4FileHandle)fileHandle error:(NSError **)outError +{ + if (!fileHandle) + return NO; + + if (_Id) + [super writeToFile:fileHandle error:outError]; + + if ([_updatedProperty valueForKey:@"volume"] || !_muxed) + MP4SetTrackFloatProperty(fileHandle, _Id, "tkhd.volume", _volume); + + if ([_updatedProperty valueForKey:@"fallback"] || !_muxed) { + if (_fallbackTrack) + _fallbackTrackId = _fallbackTrack.Id; + + if (MP4HaveTrackAtom(fileHandle, _Id, "tref.fall") && (_fallbackTrackId == 0)) { + MP4RemoveAllTrackReferences(fileHandle, "tref.fall", _Id); + } + else if (MP4HaveTrackAtom(fileHandle, _Id, "tref.fall") && (_fallbackTrackId)) { + MP4SetTrackIntegerProperty(fileHandle, _Id, "tref.fall.entries.trackId", _fallbackTrackId); + } + else if (_fallbackTrackId) + MP4AddTrackReference(fileHandle, "tref.fall", _fallbackTrackId, _Id); + } + + if ([_updatedProperty valueForKey:@"follows"] || !_muxed) { + if (_followsTrack) + _followsTrackId = _followsTrack.Id; + + if (MP4HaveTrackAtom(fileHandle, _Id, "tref.folw") && (_followsTrackId == 0)) { + MP4RemoveAllTrackReferences(fileHandle, "tref.folw", _Id); + } + else if (MP4HaveTrackAtom(fileHandle, _Id, "tref.folw") && (_followsTrackId)) { + MP4SetTrackIntegerProperty(fileHandle, _Id, "tref.folw.entries.trackId", _followsTrackId); + } + else if (_followsTrackId) + MP4AddTrackReference(fileHandle, "tref.folw", _followsTrackId, _Id); + } + + return _Id; +} + +- (NSString *)defaultName { + return MP42MediaTypeAudio; +} + +- (void)dealloc +{ + [super dealloc]; +} + +- (void)setVolume:(float)newVolume +{ + _volume = newVolume; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"volume"]; +} + +- (float)volume +{ + return _volume; +} + +- (void)setFallbackTrack:(MP42Track *)newFallbackTrack +{ + _fallbackTrack = newFallbackTrack; + _fallbackTrackId = 0; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"fallback"]; +} + +- (MP42Track *)fallbackTrack +{ + return _fallbackTrack; +} + +- (void)setFollowsTrack:(MP42Track *)newFollowsTrack +{ + _followsTrack = newFollowsTrack; + _followsTrackId = 0; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"follows"]; +} + +- (MP42Track *)followsTrack +{ + return _followsTrack; +} + +- (NSString *)formatSummary +{ + return [NSString stringWithFormat:@"%@, %u ch", _format, (unsigned int)_channels]; +} + +- (NSString *)description { + return [[super description] stringByAppendingFormat:@", %u ch", (unsigned int)_channels]; +} + +@synthesize channels = _channels; +@synthesize sourceChannels = _sourceChannels; +@synthesize mixdownType = _mixdownType; +@synthesize channelLayoutTag = _channelLayoutTag; +@synthesize fallbackTrackId = _fallbackTrackId; +@synthesize followsTrackId = _followsTrackId; + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [super encodeWithCoder:coder]; + + [coder encodeInt:1 forKey:@"MP42AudioTrackVersion"]; + + [coder encodeFloat:_volume forKey:@"volume"]; + + [coder encodeInt64:_channels forKey:@"channels"]; + [coder encodeInt64:_channelLayoutTag forKey:@"channelLayoutTag"]; + + [coder encodeInt64:_fallbackTrackId forKey:@"fallbackTrackId"]; + + [coder encodeObject:_mixdownType forKey:@"mixdownType"]; +} + +- (id)initWithCoder:(NSCoder *)decoder +{ + self = [super initWithCoder:decoder]; + + _volume = [decoder decodeFloatForKey:@"volume"]; + + _channels = [decoder decodeInt64ForKey:@"channels"]; + _channelLayoutTag = [decoder decodeInt64ForKey:@"channelLayoutTag"]; + + _fallbackTrackId = [decoder decodeInt64ForKey:@"fallbackTrackId"]; + + _mixdownType = [[decoder decodeObjectForKey:@"mixdownType"] retain]; + + return self; +} + +@end diff --git a/MP42/MP42BitmapSubConverter.h b/MP42/MP42BitmapSubConverter.h new file mode 100644 index 0000000..aa3658f --- /dev/null +++ b/MP42/MP42BitmapSubConverter.h @@ -0,0 +1,53 @@ +// +// SBVobSubConverter.h +// Subler +// +// Created by Damiano Galassi on 26/03/11. +// Copyright 2011 Damiano Galassi. All rights reserved. +// + +#import +#import "MP42ConverterProtocol.h" +#import "MP42Fifo.h" + +#include + +@class MP42SampleBuffer; +@class MP42SubtitleTrack; +@class MP42OCRWrapper; + +@interface MP42BitmapSubConverter : NSObject { + NSThread *decoderThread; + NSThread *encoderThread; + + MP42OCRWrapper *ocr; + AVCodec *avCodec; + AVCodecContext *avContext; + AVSubtitle subtitle; + + MP42Fifo *_inputSamplesBuffer; + MP42Fifo *_outputSamplesBuffer; + + int compressed; + UInt32 paletteG[16]; + NSData *srcMagicCookie; + + uint8_t *codecData; + unsigned int bufferSize; + + int32_t _readerDone; + int32_t _encoderDone; + dispatch_semaphore_t _done; +} + +- (instancetype)initWithTrack:(MP42SubtitleTrack *)track error:(NSError **)outError; + +- (void)addSample:(MP42SampleBuffer *)sample; +- (MP42SampleBuffer *)copyEncodedSample; + +- (void)cancel; + +- (BOOL)encoderDone; +- (void)setInputDone; + +@end diff --git a/MP42/MP42BitmapSubConverter.m b/MP42/MP42BitmapSubConverter.m new file mode 100644 index 0000000..05b6314 --- /dev/null +++ b/MP42/MP42BitmapSubConverter.m @@ -0,0 +1,418 @@ +// +// SBVobSubConverter.m +// Subler +// +// Created by Damiano Galassi on 26/03/11. +// VobSub code taken from Perian VobSubCodec.c +// Copyright 2011 Damiano Galassi. All rights reserved. +// + +#import "MP42BitmapSubConverter.h" +#import "MP42File.h" +#import "MP42FileImporter.h" +#import "MP42Sample.h" +#import "MP42OCRWrapper.h" +#import "MP42SubUtilities.h" + +#define REGISTER_DECODER(x) { \ +extern AVCodec ff_##x##_decoder; \ +avcodec_register(&ff_##x##_decoder); } + +void FFInitFFmpeg() +{ + static dispatch_once_t once; + + dispatch_once(&once, ^{ + REGISTER_DECODER(dvdsub); + REGISTER_DECODER(pgssub); + }); +} + +@implementation MP42BitmapSubConverter + +- (void)VobSubDecoderThreadMainRoutine:(id)sender +{ + @autoreleasepool { + while(1) { + MP42SampleBuffer *sampleBuffer = nil; + + while (!(sampleBuffer = [_inputSamplesBuffer dequeAndWait]) && !_readerDone); + + if (!sampleBuffer) + break; + + UInt8 *data = (UInt8 *) sampleBuffer->data; + int ret, got_sub; + + if(sampleBuffer->size < 4) + { + MP42SampleBuffer *subSample = copyEmptySubtitleSample(sampleBuffer->trackId, sampleBuffer->duration, NO); + + [_outputSamplesBuffer enqueue:subSample]; + [subSample release]; + + [sampleBuffer release]; + + continue; + } + + if (codecData == NULL) { + codecData = av_malloc(sampleBuffer->size + 2); + bufferSize = (unsigned int)sampleBuffer->size + 2; + } + + // make sure we have enough space to store the packet + codecData = fast_realloc_with_padding(codecData, &bufferSize, (unsigned int)sampleBuffer->size + 2); + + // the header of a spu PS packet starts 0x000001bd + // if it's raw spu data, the 1st 2 bytes are the length of the data + if (data[0] + data[1] == 0) { + // remove the MPEG framing + sampleBuffer->size = ExtractVobSubPacket(codecData, data, bufferSize, NULL, -1); + } else { + memcpy(codecData, sampleBuffer->data, sampleBuffer->size); + } + + AVPacket pkt; + av_init_packet(&pkt); + pkt.data = codecData; + pkt.size = bufferSize; + ret = avcodec_decode_subtitle2(avContext, &subtitle, &got_sub, &pkt); + + if (ret < 0 || !got_sub) { + NSLog(@"Error decoding DVD subtitle %d / %ld", ret, (long)bufferSize); + + MP42SampleBuffer *subSample = copyEmptySubtitleSample(sampleBuffer->trackId, sampleBuffer->duration, NO); + + [_outputSamplesBuffer enqueue:subSample]; + [subSample release]; + + [sampleBuffer release]; + + continue; + } + + unsigned int i, x, j, y; + uint8_t *imageData; + + OSErr err = noErr; + PacketControlData controlData; + + memcpy(paletteG, [srcMagicCookie bytes], sizeof(UInt32)*16); + int ii; + for ( ii = 0; ii <16; ii++ ) + paletteG[ii] = EndianU32_LtoN(paletteG[ii]); + + BOOL forced = NO; + err = ReadPacketControls(codecData, paletteG, &controlData, &forced); + int usePalette = 0; + + if (err == noErr) + usePalette = true; + + for (i = 0; i < subtitle.num_rects; i++) { + AVSubtitleRect *rect = subtitle.rects[i]; + + imageData = malloc(sizeof(uint8_t) * rect->w * rect->h * 4); + memset(imageData, 0, rect->w * rect->h * 4); + + uint8_t *line = (uint8_t *)imageData; + uint8_t *sub = rect->pict.data[0]; + unsigned int w = rect->w; + unsigned int h = rect->h; + uint32_t *palette = (uint32_t *)rect->pict.data[1]; + + if (usePalette) { + for (j = 0; j < 4; j++) + palette[j] = EndianU32_BtoN(controlData.pixelColor[j]); + } + + for (y = 0; y < h; y++) { + uint32_t *pixel = (uint32_t *) line; + + for (x = 0; x < w; x++) + pixel[x] = palette[sub[x]]; + + line += rect->w*4; + sub += rect->pict.linesize[0]; + } + + size_t length = sizeof(uint8_t) * rect->w * rect->h * 4; + uint8_t* imgData2 = (uint8_t*)imageData; + for (i = 0; i < length; i +=4) { + imgData2[i] = 255; + } + + CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaFirst; + CFDataRef imgData = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, imageData, w*h*4, kCFAllocatorNull); + CGDataProviderRef provider = CGDataProviderCreateWithCFData(imgData); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGImageRef cgImage = CGImageCreate(w, + h, + 8, + 32, + w*4, + colorSpace, + bitmapInfo, + provider, + NULL, + NO, + kCGRenderingIntentDefault); + CGColorSpaceRelease(colorSpace); + +#ifdef OCR_DEBUG + NSBitmapImageRep *bitmapImage = [[NSBitmapImageRep alloc]initWithCGImage:(CGImageRef)cgImage]; + [[bitmapImage representationUsingType:NSTIFFFileType properties:nil] writeToFile:@"/tmp/foo.tif" atomically:YES]; + [bitmapImage release]; +#endif + NSString *text = [ocr performOCROnCGImage:cgImage]; + + MP42SampleBuffer *subSample = nil; + if (text) + subSample = copySubtitleSample(sampleBuffer->trackId, text, sampleBuffer->duration, forced, NO, CGSizeMake(0,0), 0); + else + subSample = copyEmptySubtitleSample(sampleBuffer->trackId, sampleBuffer->duration, forced); + + [_outputSamplesBuffer enqueue:subSample]; + [subSample release]; + + CGImageRelease(cgImage); + CGDataProviderRelease(provider); + CFRelease(imgData); + + free(imageData); + } + + avsubtitle_free(&subtitle); + av_free_packet(&pkt); + + [sampleBuffer release]; + } + + _encoderDone = YES; + dispatch_semaphore_signal(_done); + } +} + +- (void)PGSDecoderThreadMainRoutine:(id)sender +{ + @autoreleasepool { + while(1) { + MP42SampleBuffer *sampleBuffer = nil; + + while (!(sampleBuffer = [_inputSamplesBuffer dequeAndWait]) && !_readerDone); + + if (!sampleBuffer) + break; + + int ret, got_sub, i; + uint32_t *imageData; + BOOL forced = NO; + + AVPacket pkt; + av_init_packet(&pkt); + pkt.data = sampleBuffer->data; + pkt.size = (int)sampleBuffer->size; + + ret = avcodec_decode_subtitle2(avContext, &subtitle, &got_sub, &pkt); + + if (ret < 0 || !got_sub || !subtitle.num_rects) { + MP42SampleBuffer *subSample = copyEmptySubtitleSample(sampleBuffer->trackId, sampleBuffer->duration, NO); + + [_outputSamplesBuffer enqueue:subSample]; + [subSample release]; + + [sampleBuffer release]; + + continue; + } + + for (i = 0; i < subtitle.num_rects; i++) { + AVSubtitleRect *rect = subtitle.rects[i]; + NSString *text; + + imageData = malloc(sizeof(uint32_t) * rect->w * rect->h * 4); + memset(imageData, 0, rect->w * rect->h * 4); + + int xx, yy; + for (yy = 0; yy < rect->h; yy++) + { + for (xx = 0; xx < rect->w; xx++) + { + uint32_t argb; + int pixel; + uint8_t color; + + pixel = yy * rect->w + xx; + color = rect->pict.data[0][pixel]; + argb = ((uint32_t*)rect->pict.data[1])[color]; + + imageData[yy * rect->w + xx] = EndianU32_BtoN(argb); + /* Remove the alpha channel, and set fully transparent pixel to black + TODO: real compositing on a black background */ + if (!(imageData[yy * rect->w + xx] & 0xFF)) + imageData[yy * rect->w + xx] = 0x000000FF; + else + imageData[yy * rect->w + xx] = (imageData[yy * rect->w + xx] & 0xFFFFFF00) + 0xFF; + } + } + + if (rect->flags & AV_SUBTITLE_FLAG_FORCED) + forced = YES; + + CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaFirst; + CFDataRef imgData = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, (uint8_t*)imageData,rect->w * rect->h * 4, kCFAllocatorNull); + CGDataProviderRef provider = CGDataProviderCreateWithCFData(imgData); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGImageRef cgImage = CGImageCreate(rect->w, + rect->h, + 8, + 32, + rect->w * 4, + colorSpace, + bitmapInfo, + provider, + NULL, + NO, + kCGRenderingIntentDefault); + CGColorSpaceRelease(colorSpace); + + MP42SampleBuffer *subSample = nil; + if ((text = [ocr performOCROnCGImage:cgImage])) + subSample = copySubtitleSample(sampleBuffer->trackId, text, sampleBuffer->duration, forced, NO, CGSizeMake(0,0), 0); + else + subSample = copyEmptySubtitleSample(sampleBuffer->trackId, sampleBuffer->duration, forced); + + [_outputSamplesBuffer enqueue:subSample]; + [subSample release]; + + CGImageRelease(cgImage); + CGDataProviderRelease(provider); + CFRelease(imgData); + + free(imageData); + } + + avsubtitle_free(&subtitle); + av_free_packet(&pkt); + + [sampleBuffer release]; + } + + _encoderDone = YES; + dispatch_semaphore_signal(_done); + } +} + +- (instancetype)initWithTrack:(MP42SubtitleTrack *) track error:(NSError **)outError +{ + if ((self = [super init])) { + if (!avCodec) { + FFInitFFmpeg(); + + if (([track.sourceFormat isEqualToString:MP42SubtitleFormatVobSub])) + avCodec = avcodec_find_decoder(AV_CODEC_ID_DVD_SUBTITLE); + else if (([track.sourceFormat isEqualToString:MP42SubtitleFormatPGS])) + avCodec = avcodec_find_decoder(AV_CODEC_ID_HDMV_PGS_SUBTITLE); + + avContext = avcodec_alloc_context3(NULL); + + if (avcodec_open2(avContext, avCodec, NULL)) { + NSLog(@"Error opening subtitle decoder"); + av_freep(&avContext); + return nil; + } + } + + _outputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:20]; + _inputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:20]; + + srcMagicCookie = [[track.muxer_helper->importer magicCookieForTrack:track] retain]; + + ocr = [[MP42OCRWrapper alloc] initWithLanguage:[track language]]; + + _done = dispatch_semaphore_create(0); + + if (([track.sourceFormat isEqualToString:MP42SubtitleFormatVobSub])) { + // Launch the vobsub decoder thread. + decoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(VobSubDecoderThreadMainRoutine:) object:self]; + [decoderThread setName:@"VobSub Decoder"]; + [decoderThread start]; + } + else if (([track.sourceFormat isEqualToString:MP42SubtitleFormatPGS])) { + // Launch the pgs decoder thread. + decoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(PGSDecoderThreadMainRoutine:) object:self]; + [decoderThread setName:@"PGS Decoder"]; + [decoderThread start]; + } + + } + + return self; +} + +- (void)addSample:(MP42SampleBuffer *)sample +{ + [_inputSamplesBuffer enqueue:sample]; +} + +- (MP42SampleBuffer *)copyEncodedSample +{ + if (![_outputSamplesBuffer count]) + return nil; + + return [_outputSamplesBuffer deque]; +} + +- (void)cancel +{ + _readerDone = YES; + + [_inputSamplesBuffer cancel]; + [_outputSamplesBuffer cancel]; + + dispatch_semaphore_wait(_done, DISPATCH_TIME_FOREVER); +} + +- (void)setInputDone +{ + _readerDone = YES; +} + +- (BOOL)encoderDone +{ + return _encoderDone; +} + +- (void)dealloc +{ + if (codecData) { + av_freep(&codecData); + } + if (avCodec) { + avcodec_close(avContext); + } + if (avContext) { + av_freep(&avContext); + } + if (subtitle.rects) { + for (int i = 0; i < subtitle.num_rects; i++) { + av_freep(&subtitle.rects[i]->pict.data[0]); + av_freep(&subtitle.rects[i]->pict.data[1]); + av_freep(&subtitle.rects[i]); + } + av_freep(&subtitle.rects); + } + + [srcMagicCookie release]; + [_outputSamplesBuffer release]; + [_inputSamplesBuffer release]; + + [decoderThread release]; + [ocr release]; + + dispatch_release(_done); + [super dealloc]; +} + +@end diff --git a/MP42/MP42CCImporter.h b/MP42/MP42CCImporter.h new file mode 100644 index 0000000..3c70db0 --- /dev/null +++ b/MP42/MP42CCImporter.h @@ -0,0 +1,15 @@ +// +// MP42CCFileImporter.h +// Subler +// +// Created by Damiano Galassi on 05/12/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import +#import "MP42FileImporter.h" + +@interface MP42CCImporter : MP42FileImporter { +} + +@end \ No newline at end of file diff --git a/MP42/MP42CCImporter.m b/MP42/MP42CCImporter.m new file mode 100644 index 0000000..ebb653e --- /dev/null +++ b/MP42/MP42CCImporter.m @@ -0,0 +1,254 @@ +// +// MP42CCFileImporter.m +// Subler +// +// Created by Damiano Galassi on 05/12/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import "MP42CCImporter.h" +#import "MP42SubUtilities.h" +#import "SBLanguages.h" +#import "MP42File.h" +#import "RegexKitLite.h" + + +@implementation MP42CCImporter + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError +{ + if ((self = [super init])) { + _fileURL = [fileURL retain]; + + _tracksArray = [[NSMutableArray alloc] initWithCapacity:1]; + + MP42Track *newTrack = [[MP42ClosedCaptionTrack alloc] init]; + + newTrack.name = @"Closed Caption Track"; + newTrack.format = MP42ClosedCaptionFormatCEA608; + newTrack.sourceURL = _fileURL; + + [_tracksArray addObject:newTrack]; + [newTrack release]; + } + + return self; +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + return 30000; +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + return NSMakeSize([(MP42SubtitleTrack*)track trackWidth], [(MP42SubtitleTrack*) track trackHeight]); +} + +- (NSData*)magicCookieForTrack:(MP42Track *)track +{ + return nil; +} + +static unsigned ParseTimeCode(const char *time, unsigned secondScale, BOOL hasSign, uint64_t *dropFrame) +{ + unsigned hour, minute, second, frame, timeval; + char separator; + int sign = 1; + + if (hasSign && *time == '-') { + sign = -1; + time++; + } + + if (sscanf(time,"%u:%u:%u%[,.:;]%u",&hour,&minute,&second,&separator,&frame) < 5) + return 0; + + timeval = (hour * 60 * 60 + minute * 60 + second) * 30 + frame; + //timeval = secondScale * timeval + frame; + + if (separator == ';') + *dropFrame = 1; + + return timeval * sign; +} + +static int ParseByte(const char *string, UInt8 *byte, Boolean hex) +{ + int err = 0; + char chars[2]; + + if (sscanf(string, "%2c", chars) == 1) + { + chars[0] = (char)tolower(chars[0]); + chars[1] = (char)tolower(chars[1]); + + if (((chars[0] >= '0' && chars[0] <= '9') || (hex && (chars[0] >= 'a' && chars[0] <= 'f'))) && + ((chars[1] >= '0' && chars[1] <= '9') || (hex && (chars[1] >= 'a' && chars[1] <= 'f')))) + { + *byte = 0; + if (chars[0] >= '0' && chars[0] <= '9') + *byte = (chars[0] - '0') * (hex ? 16 : 10); + else if (chars[0] >= 'a' && chars[0] <= 'f') + *byte = (chars[0] - 'a' + 10) * 16; + + if (chars[1] >= '0' && chars[1] <= '9') + *byte += (chars[1] - '0'); + else if (chars[1] >= 'a' && chars[1] <= 'f') + *byte += (chars[1] - 'a' + 10); + + err = 1; + } + } + + return err; +} + +- (void)demux:(id)sender +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + MP4TrackId trackId = [[_inputTracks lastObject] sourceId]; + + NSString *scc = STStandardizeStringNewlines(STLoadFileWithUnknownEncoding([_fileURL path])); + if (!scc) return; + + NSScanner *sc = [NSScanner scannerWithString:scc]; + NSString *res=nil; + [sc setCharactersToBeSkipped:nil]; + + [sc scanUpToString:@"\n" intoString:&res]; + if (![res isEqualToString:@"Scenarist_SCC V1.0"]) + return; + + unsigned startTime=0; + BOOL firstSample = YES; + NSString *splitLine = @"\\n+"; + NSString *splitTimestamp = @"\\t+"; + NSString *splitBytes = @"\\s+"; + NSArray *fileArray = nil; + NSUInteger i = 0; + + fileArray = [scc componentsSeparatedByRegex:splitLine]; + + NSMutableArray *sampleArray = [[NSMutableArray alloc] initWithCapacity:[fileArray count]]; + + uint64_t dropFrame = 0; + uint64_t frameDrop = 0; + uint64_t minutesDrop = 0; + + for (NSString *line in fileArray) { + NSArray *lineArray = [line componentsSeparatedByRegex:splitTimestamp]; + + if ([lineArray count] < 2) + continue; + + startTime = ParseTimeCode([[lineArray objectAtIndex:0] UTF8String], 30000, NO, &dropFrame); + SBTextSample *sample = [[SBTextSample alloc] init]; + sample.timestamp = startTime; + sample.title = [lineArray lastObject]; + + [sampleArray addObject:[sample autorelease]]; + } + + for (SBTextSample *ccSample in sampleArray) { + if (_cancelled) + break; + + NSArray *bytesArray = nil; + MP4Duration sampleDuration = 0; + bytesArray = [ccSample.title componentsSeparatedByRegex:splitBytes]; + + NSUInteger byteCount = [bytesArray count] *2; + UInt8 *bytes = malloc(sizeof(UInt8)*byteCount*2 + (sizeof(UInt8)*8)); + UInt8 *bytesPos = bytes; + + // Write out the size of the atom + *(long*)bytesPos = EndianS32_NtoB(8 + byteCount); + bytesPos += sizeof(long); + + // Write out the atom type + *(OSType*)bytesPos = EndianU32_NtoB('cdat'); + bytesPos += sizeof(OSType); + + for (NSString *hexByte in bytesArray) { + ParseByte([hexByte UTF8String], bytesPos , 1); + ParseByte([hexByte UTF8String] + 2, bytesPos + 1, 1); + bytesPos +=2; + } + + if (firstSample && ccSample.timestamp != 0 && i == 0) { + SBTextSample *boh = [sampleArray objectAtIndex:1]; + sampleDuration = boh.timestamp - ccSample.timestamp; + firstSample = NO; + u_int8_t *emptyBuffer = malloc(sizeof(u_int8_t)*8); + u_int8_t empty[8] = {0,0,0,8,'c','d','a','t'}; + memcpy(emptyBuffer, empty, sizeof(u_int8_t)*8); + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = emptyBuffer; + sample->size = 8; + sample->duration = ccSample.timestamp *= 1001; + sample->offset = 0; + sample->timestamp = 0; + sample->isSync = 1; + sample->trackId = trackId; + + [self enqueue:sample]; + [sample release]; + + frameDrop += ccSample.timestamp; + minutesDrop += frameDrop; + } + else if (i+1 < [sampleArray count]) { + SBTextSample *boh = [sampleArray objectAtIndex:i+1]; + sampleDuration = boh.timestamp - ccSample.timestamp; + frameDrop += sampleDuration; + minutesDrop += sampleDuration; + + if (frameDrop >= 1800 && dropFrame) { + if (minutesDrop > 18000) + minutesDrop -= 16200; + else { + sampleDuration -= 2; + } + + frameDrop -= 1800; + } + } + else + sampleDuration = 6; + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = bytes; + sample->size = byteCount + 8; + sample->duration = sampleDuration * 1001; + sample->offset = 0; + sample->timestamp = 0; + sample->isSync = 1; + sample->trackId = trackId; + + [self enqueue:sample]; + [sample release]; + + i++; + _progress = ((CGFloat)i / [sampleArray count]) * 100; + } + + [sampleArray release]; + [self setDone:YES]; + + [pool release]; +} + +- (void)startReading +{ + [super startReading]; + + if (!_demuxerThread && !_done) { + _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; + [_demuxerThread setName:@"Closed Caption Demuxer"]; + [_demuxerThread start]; + } +} + +@end diff --git a/MP42/MP42ChapterTrack.h b/MP42/MP42ChapterTrack.h new file mode 100644 index 0000000..879a8a1 --- /dev/null +++ b/MP42/MP42ChapterTrack.h @@ -0,0 +1,34 @@ +// +// MP42ChapterTrack.h +// Subler +// +// Created by Damiano Galassi on 06/02/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import +#import "MP42Track.h" + +@class SBTextSample; + +@interface MP42ChapterTrack : MP42Track { + NSMutableArray *chapters; +} +- (instancetype)initWithSourceURL:(NSURL *)URL trackID:(NSInteger)trackID fileHandle:(MP42FileHandle)fileHandle; ++ (instancetype)chapterTrackFromFile:(NSURL *)URL; + +- (void)addChapter:(NSString *)title duration:(uint64_t)timestamp; +- (void)removeChapterAtIndex:(NSUInteger)index; + +- (void)setTimestamp:(MP42Duration)timestamp forChapter:(SBTextSample *)chapterSample; +- (void)setTitle:(NSString*)title forChapter:(SBTextSample *)chapterSample; + +- (SBTextSample *)chapterAtIndex:(NSUInteger)index; + +- (NSInteger)chapterCount; + +- (BOOL)exportToURL:(NSURL *)url error:(NSError **)error; + +@property(nonatomic, readonly, retain) NSArray *chapters; + +@end diff --git a/MP42/MP42ChapterTrack.m b/MP42/MP42ChapterTrack.m new file mode 100644 index 0000000..60b0f3e --- /dev/null +++ b/MP42/MP42ChapterTrack.m @@ -0,0 +1,271 @@ +// +// MP42ChapterTrack.m +// Subler +// +// Created by Damiano Galassi on 06/02/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import "MP42ChapterTrack.h" +#import "MP42SubUtilities.h" +#import "MP42Utilities.h" +#import "MP42MediaFormat.h" + +@implementation MP42ChapterTrack + +- (instancetype)init +{ + if ((self = [super init])) { + _name = [self defaultName]; + _format = MP42SubtitleFormatText; + _language = @"English"; + _isEdited = YES; + _muxed = NO; + _enabled = NO; + _mediaType = MP42MediaTypeText; + + chapters = [[NSMutableArray alloc] init]; + } + + return self; +} + +- (instancetype)initWithSourceURL:(NSURL *)URL trackID:(NSInteger)trackID fileHandle:(MP4FileHandle)fileHandle +{ + if ((self = [super initWithSourceURL:URL trackID:trackID fileHandle:fileHandle])) { + if (!_name || [_name isEqualToString:@"Text Track"]) + _name = [self defaultName]; + if (!_format) + _format = MP42SubtitleFormatText; + + _mediaType = MP42MediaTypeText; + chapters = [[NSMutableArray alloc] init]; + + MP4Chapter_t *chapter_list = NULL; + uint32_t chapter_count; + + MP4GetChapters(fileHandle, &chapter_list, &chapter_count, MP4ChapterTypeQt); + + unsigned int i = 1; + MP4Duration sum = 0; + while (i <= chapter_count) + { + SBTextSample *chapter = [[SBTextSample alloc] init]; + + char * title = chapter_list[i-1].title; + if ((title[0] == '\xfe' && title[1] == '\xff') || (title[0] == '\xff' && title[1] == '\xfe')) { + chapter.title = [[[NSString alloc] initWithBytes:title + length:chapter_list[i-1].titleLength + encoding:NSUTF16StringEncoding] autorelease]; + } + else { + chapter.title = [NSString stringWithCString:chapter_list[i-1].title encoding: NSUTF8StringEncoding]; + } + + chapter.timestamp = sum; + sum = chapter_list[i-1].duration + sum; + [chapters addObject:chapter]; + [chapter release]; + i++; + } + MP4Free(chapter_list); + } + + return self; +} + +- (instancetype)initWithTextFile:(NSURL *)URL +{ + if ((self = [super init])) { + _name = [self defaultName]; + _format = MP42SubtitleFormatText; + _sourceURL = [URL retain]; + _language = @"English"; + _isEdited = YES; + _muxed = NO; + _enabled = NO; + _mediaType = MP42MediaTypeText; + + chapters = [[NSMutableArray alloc] init]; + LoadChaptersFromPath([_sourceURL path], chapters); + [chapters sortUsingSelector:@selector(compare:)]; + } + + return self; +} + ++ (instancetype)chapterTrackFromFile:(NSURL *)URL +{ + return [[[MP42ChapterTrack alloc] initWithTextFile:URL] autorelease]; +} + +- (void)addChapter:(NSString *)title duration:(uint64_t)timestamp +{ + SBTextSample *newChapter = [[SBTextSample alloc] init]; + newChapter.title = title; + newChapter.timestamp = timestamp; + + _isEdited = YES; + + [chapters addObject:newChapter]; + [chapters sortUsingSelector:@selector(compare:)]; + [newChapter release]; +} + +- (void)removeChapterAtIndex:(NSUInteger)index +{ + _isEdited = YES; + [chapters removeObjectAtIndex:index]; +} + +- (void)setTimestamp:(MP4Duration)timestamp forChapter:(SBTextSample *)chapterSample +{ + _isEdited = YES; + [chapterSample setTimestamp:timestamp]; + [chapters sortUsingSelector:@selector(compare:)]; +} + +- (void)setTitle:(NSString *)title forChapter:(SBTextSample *)chapterSample +{ + _isEdited = YES; + [chapterSample setTitle:title]; +} + +- (SBTextSample *)chapterAtIndex:(NSUInteger)index +{ + return [chapters objectAtIndex:index]; +} + +- (BOOL)writeToFile:(MP4FileHandle)fileHandle error:(NSError **)outError +{ + BOOL success = YES; + + if (_isEdited) { + MP4Chapter_t * fileChapters = 0; + MP4Duration refTrackDuration; + uint32_t chapterCount = 0; + uint32_t i = 0; + uint64_t sum = 0, moovDuration; + + // get the list of chapters + MP4GetChapters(fileHandle, &fileChapters, &chapterCount, MP4ChapterTypeQt); + + MP4DeleteChapters(fileHandle, MP4ChapterTypeAny, _Id); + updateTracksCount(fileHandle); + + MP4TrackId refTrack = findFirstVideoTrack(fileHandle); + if (!refTrack) + refTrack = 1; + + chapterCount = [chapters count]; + + if (chapterCount) { + // Insert a chapter at time 0 if there isn't one + SBTextSample * chapter = [chapters objectAtIndex:0]; + if (chapter.timestamp != 0) { + SBTextSample *st = [[SBTextSample alloc] init]; + st.timestamp = 0; + st.title = @"Chapter 0"; + [chapters insertObject:st atIndex:0]; + [st release]; + chapterCount++; + } + + fileChapters = malloc(sizeof(MP4Chapter_t)*chapterCount); + refTrackDuration = MP4ConvertFromTrackDuration(fileHandle, + refTrack, + MP4GetTrackDuration(fileHandle, refTrack), + MP4_MSECS_TIME_SCALE); + MP4GetIntegerProperty(fileHandle, "moov.mvhd.duration", &moovDuration); + moovDuration = (uint64_t) moovDuration * (double) 1000 / MP4GetTimeScale(fileHandle); + if (refTrackDuration > moovDuration) + refTrackDuration = moovDuration; + + for (i = 0; i < chapterCount; i++) { + SBTextSample * chapter = [chapters objectAtIndex:i]; + if ([[chapter title] UTF8String]) + strcpy(fileChapters[i].title, [[chapter title] UTF8String]); + + if (i + 1 < chapterCount && sum < refTrackDuration) { + SBTextSample * nextChapter = [chapters objectAtIndex:i+1]; + fileChapters[i].duration = nextChapter.timestamp - chapter.timestamp; + sum = nextChapter.timestamp; + } + else + fileChapters[i].duration = refTrackDuration - chapter.timestamp; + + if (sum > refTrackDuration) { + fileChapters[i].duration = refTrackDuration - chapter.timestamp; + i++; + break; + } + } + + removeAllChapterTrackReferences(fileHandle); + MP4SetChapters(fileHandle, fileChapters, i, MP4ChapterTypeAny); + + free(fileChapters); + success = _Id = findChapterTrackId(fileHandle); + } + } + if (!success) { + if ( outError != NULL) + *outError = MP42Error(@"Failed to mux chapters into mp4 file", + nil, + 120); + + return success; + } + else if (_Id) + success = [super writeToFile:fileHandle error:outError]; + + return success; +} + +- (NSInteger)chapterCount +{ + return [chapters count]; +} + +- (BOOL)exportToURL:(NSURL *)url error:(NSError **)error +{ + NSMutableString* file = [[[NSMutableString alloc] init] autorelease]; + NSUInteger x = 0; + + for (SBTextSample * chapter in chapters) { + [file appendFormat:@"CHAPTER%02lu=%@\nCHAPTER%02luNAME=%@\n", (unsigned long)x, SRTStringFromTime([chapter timestamp], 1000, '.'), (unsigned long)x, [chapter title]]; + x++; + } + + return [file writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:error]; +} + +- (NSString *)defaultName { + return @"Chapter Track"; +} + +@synthesize chapters; + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [super encodeWithCoder:coder]; + + [coder encodeObject:chapters forKey:@"chapters"]; +} + +- (id)initWithCoder:(NSCoder *)decoder +{ + self = [super initWithCoder:decoder]; + + chapters = [[decoder decodeObjectForKey:@"chapters"] retain]; + + return self; +} + +- (void)dealloc +{ + [chapters release]; + [super dealloc]; +} + +@end diff --git a/MP42/MP42ClosedCaptionTrack.h b/MP42/MP42ClosedCaptionTrack.h new file mode 100644 index 0000000..3935145 --- /dev/null +++ b/MP42/MP42ClosedCaptionTrack.h @@ -0,0 +1,14 @@ +// +// MP42SubtitleTrack.h +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import +#import "MP42VideoTrack.h" + +@interface MP42ClosedCaptionTrack : MP42VideoTrack + +@end diff --git a/MP42/MP42ClosedCaptionTrack.m b/MP42/MP42ClosedCaptionTrack.m new file mode 100644 index 0000000..bbab435 --- /dev/null +++ b/MP42/MP42ClosedCaptionTrack.m @@ -0,0 +1,54 @@ +// +// MP42SubtitleTrack.m +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import "MP42ClosedCaptionTrack.h" +#import "MP42MediaFormat.h" +#import "SBLanguages.h" + +@implementation MP42ClosedCaptionTrack + +- (instancetype)initWithSourceURL:(NSURL *)URL trackID:(NSInteger)trackID fileHandle:(MP42FileHandle)fileHandle +{ + if (self = [super initWithSourceURL:URL trackID:trackID fileHandle:fileHandle]) { + _mediaType = MP42MediaTypeClosedCaption; + } + + return self; +} + +- (instancetype)init +{ + if ((self = [super init])) { + _name = [self defaultName]; + _format = MP42ClosedCaptionFormatCEA608; + _mediaType = MP42MediaTypeClosedCaption; + } + + return self; +} + +- (BOOL)writeToFile:(MP42FileHandle)fileHandle error:(NSError **)outError +{ + if (_isEdited && !_muxed) + _muxed = YES; + + [super writeToFile:fileHandle error:outError]; + + return _Id; +} + +- (NSString *)defaultName { + return MP42MediaTypeClosedCaption; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@end diff --git a/MP42/MP42ConverterProtocol.h b/MP42/MP42ConverterProtocol.h new file mode 100644 index 0000000..21afcb1 --- /dev/null +++ b/MP42/MP42ConverterProtocol.h @@ -0,0 +1,26 @@ +// +// MP42ConverterProtocol.h +// Subler +// +// Created by Damiano Galassi on 05/08/13. +// +// + +#import +#import "MP42Sample.h" + +@protocol MP42ConverterProtocol + +@optional +- (NSData *)magicCookie; + +@required +- (void)addSample:(MP42SampleBuffer *)sample; +- (MP42SampleBuffer *)copyEncodedSample; + +- (void)cancel; +- (BOOL)encoderDone; + +- (void)setInputDone; + +@end diff --git a/MP42/MP42Fifo.h b/MP42/MP42Fifo.h new file mode 100644 index 0000000..6eb6aa6 --- /dev/null +++ b/MP42/MP42Fifo.h @@ -0,0 +1,41 @@ +// +// MP42Fifo.h +// Subler +// +// Created by Damiano Galassi on 09/08/13. +// +// + +#import + +@interface MP42Fifo : NSObject { + id *_array; + + int32_t _head; + int32_t _tail; + + int32_t _count; + int32_t _size; + + int32_t _cancelled; + + dispatch_semaphore_t _full; + dispatch_semaphore_t _empty; +} + +- (instancetype)init; +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +- (void)enqueue:(id)item; +- (id)deque NS_RETURNS_RETAINED; +- (id)dequeAndWait NS_RETURNS_RETAINED; + +- (NSInteger)count; + +- (BOOL)isFull; +- (BOOL)isEmpty; + +- (void)drain; +- (void)cancel; + +@end diff --git a/MP42/MP42Fifo.m b/MP42/MP42Fifo.m new file mode 100644 index 0000000..e3fbb83 --- /dev/null +++ b/MP42/MP42Fifo.m @@ -0,0 +1,103 @@ +// +// MP42Fifo.m +// Subler +// +// Created by Damiano Galassi on 09/08/13. +// +// + +#import "MP42Fifo.h" + +@implementation MP42Fifo + +- (instancetype)init { + self = [self initWithCapacity:300]; + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + self = [super init]; + if (self) { + _size = (int32_t)numItems; + _array = (id *) malloc(sizeof(id) * _size); + _full = dispatch_semaphore_create(_size); + _empty = dispatch_semaphore_create(0); + + } + return self; +} + +- (void)enqueue:(id)item { + if (_cancelled) return; + + [item retain]; + + dispatch_semaphore_wait(_full, DISPATCH_TIME_FOREVER); + + _array[_tail++] = item; + + if (_tail == _size) + _tail = 0; + + OSAtomicIncrement32(&_count); + dispatch_semaphore_signal(_empty); +} + +- (id)deque { + if (!_count) return nil; + + id item = _array[_head++]; + + if (_head == _size) + _head = 0; + + OSAtomicDecrement32(&_count); + dispatch_semaphore_signal(_full); + + return item; +} + +- (id)dequeAndWait { + id item = [self deque]; + + if (!item) { + dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC/1000); + dispatch_semaphore_wait(_empty, time); + } + + return item; +} + +- (NSInteger)count { + return _count; +} + +- (BOOL)isFull { + return (_count >= _size); +} + +- (BOOL)isEmpty { + return !_count; +} + +- (void)drain { + while (![self isEmpty]) + [[self deque] release]; +} + +- (void)cancel { + OSAtomicIncrement32(&_cancelled); + [self drain]; +} + +- (void)dealloc { + [self drain]; + + free(_array); + dispatch_release(_full); + dispatch_release(_empty); + + [super dealloc]; +} + +@end diff --git a/MP42/MP42File.h b/MP42/MP42File.h new file mode 100644 index 0000000..d65e268 --- /dev/null +++ b/MP42/MP42File.h @@ -0,0 +1,67 @@ +// +// MP42File.h +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import + +#import "MP42Track.h" +#import "MP42VideoTrack.h" +#import "MP42AudioTrack.h" +#import "MP42SubtitleTrack.h" +#import "MP42ClosedCaptionTrack.h" +#import "MP42ChapterTrack.h" +#import "MP42Metadata.h" + +#import "MP42MediaFormat.h" + +extern NSString * const MP42Create64BitData; +extern NSString * const MP42Create64BitTime; +extern NSString * const MP42CreateChaptersPreviewTrack; +extern NSString * const MP42OrganizeAlternateGroups; + +@protocol MP42FileDelegate +@optional +- (void)progressStatus:(CGFloat)progress; +- (void)endSave:(id)sender; +@end + +@interface MP42File : NSObject + +@property(readwrite, assign) id delegate; + +@property(readonly) NSURL *URL; +@property(readonly) MP42Metadata *metadata; +@property(readonly, copy) NSArray *tracks; + +@property(readonly) BOOL hasFileRepresentation; +@property(readonly) NSUInteger duration; +@property(readonly) uint64_t dataSize; + +- (instancetype)initWithDelegate:(id )del; +- (instancetype)initWithExistingFile:(NSURL *)URL andDelegate:(id )del; + +- (NSUInteger)tracksCount; +- (MP42Track *)trackAtIndex:(NSUInteger)index; +- (MP42Track *)trackWithTrackID:(NSUInteger)trackId; +- (NSArray *)tracksWithMediaType:(NSString *)mediaType; + +- (void)addTrack:(MP42Track *)track; + +- (void)removeTrackAtIndex:(NSUInteger)index; +- (void)removeTracksAtIndexes:(NSIndexSet *)indexes; +- (void)moveTrackAtIndex:(NSUInteger)index toIndex:(NSUInteger)newIndex; + +- (MP42ChapterTrack *)chapters; +- (void)organizeAlternateGroups; + +- (BOOL)writeToUrl:(NSURL *)url withAttributes:(NSDictionary *)attributes error:(NSError **)outError; +- (BOOL)updateMP4FileWithAttributes:(NSDictionary *)attributes error:(NSError **)outError; +- (BOOL)optimize; + +- (void)cancel; + +@end diff --git a/MP42/MP42File.m b/MP42/MP42File.m new file mode 100644 index 0000000..f360647 --- /dev/null +++ b/MP42/MP42File.m @@ -0,0 +1,929 @@ +// +// MP42File.m +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import "MP42File.h" +#import "MP42FileImporter.h" +#import "MP42Muxer.h" +#import "MP42SubUtilities.h" +#import "MP42Utilities.h" +#import "SBLanguages.h" + +#import + +#if __MAC_OS_X_VERSION_MAX_ALLOWED > 1060 +#import +#endif + +#import "mp4v2.h" + +NSString * const MP42Create64BitData = @"MP4264BitData"; +NSString * const MP42Create64BitTime = @"MP4264BitTime"; +NSString * const MP42CreateChaptersPreviewTrack = @"MP42ChaptersPreview"; +NSString * const MP42OrganizeAlternateGroups = @"MP42AlternateGroups"; + +@interface MP42File () { + MP4FileHandle _fileHandle; + NSURL *_fileURL; + id _delegate; + + NSMutableArray *_tracksToBeDeleted; + NSMutableDictionary *_importers; + + BOOL _hasFileRepresentation; + BOOL _cancelled; + + NSMutableArray *_tracks; + MP42Metadata *_metadata; + MP42Muxer *_muxer; +} + +- (void)reconnectReferences; +- (void)removeMuxedTrack:(MP42Track *)track; + +- (void)organizeAlternateGroupsForMediaType:(NSString *)mediaType withGroupID:(NSUInteger)groupID; + +- (NSArray *)generatePreviewImagesQTKitFromChapters:(NSArray *)chapters andFile:(NSURL *)file; +- (NSArray *)generatePreviewImagesAVFoundationFromChapters:(NSArray *)chapters andFile:(NSURL *)file; + +- (BOOL)createChaptersPreview; + +@end + +@implementation MP42File { + +} + +- (id)init +{ + if ((self = [super init])) { + _hasFileRepresentation = NO; + _tracks = [[NSMutableArray alloc] init]; + _tracksToBeDeleted = [[NSMutableArray alloc] init]; + + _metadata = [[MP42Metadata alloc] init]; + _importers = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (instancetype)initWithDelegate:(id )del; +{ + if ((self = [self init])) { + _delegate = del; + } + + return self; +} + +- (instancetype)initWithExistingFile:(NSURL *)URL andDelegate:(id )del; +{ + if ((self = [super init])) + { + _delegate = del; + _fileHandle = MP4Read([[URL path] UTF8String]); + + if (!_fileHandle) { + [self release]; + return nil; + } + + const char *brand = NULL; + MP4GetStringProperty(_fileHandle, "ftyp.majorBrand", &brand); + if (brand != NULL) { + if (!strcmp(brand, "qt ")) { + MP4Close(_fileHandle, 0); + [self release]; + return nil; + } + } + + _fileURL = [URL retain]; + _hasFileRepresentation = YES; + + _tracks = [[NSMutableArray alloc] init]; + int i, tracksCount = MP4GetNumberOfTracks(_fileHandle, 0, 0); + MP4TrackId chapterId = findChapterTrackId(_fileHandle); + + for (i=0; i< tracksCount; i++) { + id track; + MP4TrackId trackId = MP4FindTrackId(_fileHandle, i, 0, 0); + const char* type = MP4GetTrackType(_fileHandle, trackId); + + if (MP4_IS_AUDIO_TRACK_TYPE(type)) + track = [MP42AudioTrack alloc]; + else if (MP4_IS_VIDEO_TRACK_TYPE(type)) + track = [MP42VideoTrack alloc]; + else if (!strcmp(type, MP4_TEXT_TRACK_TYPE)) { + if (trackId == chapterId) + track = [MP42ChapterTrack alloc]; + else + track = [MP42Track alloc]; + } + else if (!strcmp(type, MP4_SUBTITLE_TRACK_TYPE)) + track = [MP42SubtitleTrack alloc]; + else if (!strcmp(type, MP4_SUBPIC_TRACK_TYPE)) + track = [MP42SubtitleTrack alloc]; + else if (!strcmp(type, MP4_CC_TRACK_TYPE)) + track = [MP42ClosedCaptionTrack alloc]; + else + track = [MP42Track alloc]; + + track = [track initWithSourceURL:_fileURL trackID:trackId fileHandle:_fileHandle]; + [_tracks addObject:track]; + [track release]; + } + + [self reconnectReferences]; + + _tracksToBeDeleted = [[NSMutableArray alloc] init]; + _metadata = [[MP42Metadata alloc] initWithSourceURL:_fileURL fileHandle:_fileHandle]; + _importers = [[NSMutableDictionary alloc] init]; + MP4Close(_fileHandle, 0); + } + + return self; +} + +- (void)reconnectReferences { + for (MP42Track *ref in _tracks) { + if ([ref isMemberOfClass:[MP42AudioTrack class]]) { + MP42AudioTrack *a = (MP42AudioTrack *)ref; + if (a.fallbackTrackId) + a.fallbackTrack = [self trackWithTrackID:a.fallbackTrackId]; + if (a.followsTrackId) + a.followsTrack = [self trackWithTrackID:a.followsTrackId]; + } + if ([ref isMemberOfClass:[MP42SubtitleTrack class]]) { + MP42SubtitleTrack *a = (MP42SubtitleTrack *)ref; + if (a.forcedTrackId) + a.forcedTrack = [self trackWithTrackID:a.forcedTrackId]; + } + } +} + +- (NSUInteger)duration +{ + NSUInteger duration = 0; + NSUInteger trackDuration = 0; + for (MP42Track *track in _tracks) + if ((trackDuration = [track duration]) > duration) + duration = trackDuration; + + return duration; +} + +- (MP42ChapterTrack *)chapters +{ + MP42ChapterTrack *chapterTrack = nil; + + for (MP42Track *track in _tracks) + if ([track isMemberOfClass:[MP42ChapterTrack class]]) + chapterTrack = (MP42ChapterTrack*) track; + + return [[chapterTrack retain] autorelease]; +} + +- (NSUInteger)tracksCount +{ + return [_tracks count]; +} + +- (id)trackAtIndex:(NSUInteger)index +{ + return [_tracks objectAtIndex:index]; +} + +- (id)trackWithTrackID:(NSUInteger)trackId +{ + for (MP42Track *track in _tracks) { + if (track.Id == trackId) + return track; + } + + return nil; +} + +- (NSArray *)tracksWithMediaType:(NSString *)mediaType +{ + NSMutableArray *tracks = [[[NSMutableArray alloc] init] autorelease]; + + for (MP42Track *track in _tracks) { + if ([track.mediaType isEqualToString:mediaType]) + [tracks addObject:track]; + } + + return [[tracks copy] autorelease]; +} + +- (void)addTrack:(MP42Track *)track +{ + track.sourceId = track.Id; + track.Id = 0; + track.muxed = NO; + track.isEdited = YES; + + track.language = track.language; + track.name = track.name; + if ([track isMemberOfClass:[MP42ChapterTrack class]]) { + for (id previousTrack in _tracks) + if ([previousTrack isMemberOfClass:[MP42ChapterTrack class]]) { + [_tracks removeObject:previousTrack]; + break; + } + } + + if (trackNeedConversion(track.format) || track.needConversion) { + track.needConversion = YES; + track.sourceFormat = track.format; + if ([track isMemberOfClass:[MP42AudioTrack class]]) { + MP42AudioTrack *audioTrack = (MP42AudioTrack *)track; + track.format = MP42AudioFormatAAC; + audioTrack.sourceChannels = audioTrack.channels; + if ([audioTrack.mixdownType isEqualToString:SBMonoMixdown] || audioTrack.sourceChannels == 1) + audioTrack.channels = 1; + else if (audioTrack.mixdownType) + audioTrack.channels = 2; + } + else if ([track isMemberOfClass:[MP42SubtitleTrack class]]) + track.format = MP42SubtitleFormatTx3g; + } + + if (track.muxer_helper->importer && track.sourceURL) { + if ([_importers objectForKey:[[track sourceURL] path]]) + track.muxer_helper->importer = [_importers objectForKey:[[track sourceURL] path]]; + else + [_importers setObject:track.muxer_helper->importer forKey:[[track sourceURL] path]]; + } + + [_tracks addObject:track]; +} + +- (void)removeTrackAtIndex:(NSUInteger) index +{ + [self removeTracksAtIndexes:[NSIndexSet indexSetWithIndex:index]]; +} + +- (void)removeTracksAtIndexes:(NSIndexSet *)indexes +{ + NSUInteger index = [indexes firstIndex]; + while (index != NSNotFound) { + MP42Track *track = [_tracks objectAtIndex:index]; + + // track is muxed, it needs to be removed from the file + if (track.muxed) + [_tracksToBeDeleted addObject:track]; + + // Remove the reference + for (MP42Track *ref in _tracks) { + if ([ref isMemberOfClass:[MP42AudioTrack class]]) { + MP42AudioTrack *a = (MP42AudioTrack *)ref; + if (a.fallbackTrack == track) + a.fallbackTrack = nil; + if (a.followsTrack == track) + a.followsTrack = nil; + } + if ([ref isMemberOfClass:[MP42SubtitleTrack class]]) { + MP42SubtitleTrack *a = (MP42SubtitleTrack *)ref; + if (a.forcedTrack == track) + a.forcedTrack = nil; + } + } + index = [indexes indexGreaterThanIndex:index]; + } + + [_tracks removeObjectsAtIndexes:indexes]; +} + +- (void)moveTrackAtIndex:(NSUInteger)index toIndex:(NSUInteger) newIndex +{ + id track = [[_tracks objectAtIndex:index] retain]; + + [_tracks removeObjectAtIndex:index]; + if (newIndex > [_tracks count] || newIndex > index) + newIndex--; + [_tracks insertObject:track atIndex:newIndex]; + [track release]; +} + +- (BOOL)optimize +{ + __block BOOL noErr = NO; + __block BOOL done = NO; + + @autoreleasepool { + NSError *error; + + NSFileManager *fileManager = [[NSFileManager alloc] init]; +#ifdef SB_SANDBOX + NSURL *folderURL = [fileURL URLByDeletingLastPathComponent]; + NSURL *tempURL = [fileManager URLForDirectory:NSItemReplacementDirectory inDomain:NSUserDomainMask appropriateForURL:folderURL create:YES error:&error]; +#else + NSURL *tempURL = [_fileURL URLByDeletingLastPathComponent]; +#endif + if (tempURL) { + tempURL = [tempURL URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.tmp", [_fileURL lastPathComponent]]]; + + unsigned long long originalFileSize = [[[fileManager attributesOfItemAtPath:[_fileURL path] error:nil] valueForKey:NSFileSize] unsignedLongLongValue]; + + dispatch_async(dispatch_get_global_queue(0, 0), ^{ + noErr = MP4Optimize([[_fileURL path] UTF8String], [[tempURL path] UTF8String]); + done = YES; + }); + + while (!done) { + unsigned long long fileSize = [[[fileManager attributesOfItemAtPath:[tempURL path] error:nil] valueForKey:NSFileSize] unsignedLongLongValue]; + [self progressStatus:((CGFloat)fileSize / originalFileSize) * 100]; + usleep(450000); + } + + if (noErr) { + NSURL *result = nil; + noErr = [fileManager replaceItemAtURL:_fileURL withItemAtURL:tempURL backupItemName:nil options:0 resultingItemURL:&result error:&error]; + if (noErr) { + [_fileURL release]; + _fileURL = [result retain]; + } + } + } + + [fileManager release]; + } + + if ([_delegate respondsToSelector:@selector(endSave:)]) + [_delegate performSelector:@selector(endSave:) withObject:self]; + + return noErr; +} + +- (BOOL)writeToUrl:(NSURL *)url withAttributes:(NSDictionary *)attributes error:(NSError **)outError +{ + BOOL success = YES; + + if (!url && outError) { + *outError = MP42Error(@"Invalid path.", @"The destination path cannot be empty.", 100); + return NO; + } + + if ([self hasFileRepresentation]) { + __block BOOL noErr = YES; + + if (![_fileURL isEqualTo:url]) { + __block BOOL done = NO; + NSFileManager *fileManager = [[NSFileManager alloc] init]; + unsigned long long originalFileSize = [[[fileManager attributesOfItemAtPath:[_fileURL path] error:NULL] valueForKey:NSFileSize] unsignedLongLongValue]; + + dispatch_async(dispatch_get_global_queue(0, 0), ^{ + noErr = [fileManager copyItemAtURL:_fileURL toURL:url error:outError]; + done = YES; + }); + + while (!done) { + unsigned long long fileSize = [[[fileManager attributesOfItemAtPath:[url path] error:NULL] valueForKey:NSFileSize] unsignedLongLongValue]; + [self progressStatus:((CGFloat)fileSize / originalFileSize) * 100]; + usleep(450000); + } + [fileManager release]; + } + + if (noErr) { + _fileURL = [url retain]; + success = [self updateMP4FileWithAttributes:attributes error:outError]; + } + else + success = NO; + } + else { + _fileURL = [url retain]; + + NSString *fileExtension = [_fileURL pathExtension]; + char *majorBrand = "mp42"; + char *supportedBrands[4]; + uint32_t supportedBrandsCount = 0; + uint32_t flags = 0; + + if ([[attributes valueForKey:MP42Create64BitData] boolValue]) + flags += 0x01; + + if ([[attributes valueForKey:MP42Create64BitTime] boolValue]) + flags += 0x02; + + if ([fileExtension isEqualToString:MP42FileTypeM4V]) { + majorBrand = "M4V "; + supportedBrands[0] = majorBrand; + supportedBrands[1] = "M4A "; + supportedBrands[2] = "mp42"; + supportedBrands[3] = "isom"; + supportedBrandsCount = 4; + } + else if ([fileExtension isEqualToString:MP42FileTypeM4A] || [fileExtension isEqualToString:MP42FileTypeM4A]) { + majorBrand = "M4A "; + supportedBrands[0] = majorBrand; + supportedBrands[1] = "mp42"; + supportedBrands[2] = "isom"; + supportedBrandsCount = 3; + } + else { + supportedBrands[0] = majorBrand; + supportedBrands[1] = "isom"; + supportedBrandsCount = 2; + } + + _fileHandle = MP4CreateEx([[_fileURL path] UTF8String], + flags, 1, 1, + majorBrand, 0, + supportedBrands, supportedBrandsCount); + if (_fileHandle) { + MP4SetTimeScale(_fileHandle, 600); + MP4Close(_fileHandle, 0); + + success = [self updateMP4FileWithAttributes:attributes error:outError]; + } + } + + return success; +} + +- (BOOL)updateMP4FileWithAttributes:(NSDictionary *)attributes error:(NSError **)outError +{ + BOOL noErr = YES; + + // Open the mp4 file + _fileHandle = MP4Modify([[_fileURL path] UTF8String], 0); + if (_fileHandle == MP4_INVALID_FILE_HANDLE) { + if (outError) + *outError = MP42Error(@"Unable to open the file", nil, 100); + return NO; + } + + // Delete tracks + for (MP42Track *track in _tracksToBeDeleted) + [self removeMuxedTrack:track]; + + // Init the muxer and prepare the work + _muxer = [[MP42Muxer alloc] initWithDelegate:self]; + + for (MP42Track *track in _tracks) { + if (!track.muxed) { + // Reopen the file importer is they are not already open + // this happens when the object was unarchived from a file + if (![track isMemberOfClass:[MP42ChapterTrack class]] && !track.muxer_helper->importer && [track sourceURL]) { + MP42FileImporter *fileImporter = [_importers valueForKey:[[track sourceURL] path]]; + + if (!fileImporter) { + fileImporter = [[[MP42FileImporter alloc] initWithURL:[track sourceURL] error:outError] autorelease]; + [_importers setObject:fileImporter forKey:[[track sourceURL] path]]; + } + + if (fileImporter) { + track.muxer_helper->importer = fileImporter; + } else { + *outError = MP42Error(@"Missing sources.", + @"One or more sources files are missing.", + 200); + noErr = NO; + break; + } + + } + + // Add the track to the muxer + if (track.muxer_helper->importer) + [_muxer addTrack:track]; + } + } + + if (!noErr) { + [_muxer release], _muxer = nil; + MP4Close(_fileHandle, 0); + return NO; + } + + noErr = [_muxer setup:_fileHandle error:outError]; + + if (!noErr) { + [_muxer release], _muxer = nil; + MP4Close(_fileHandle, 0); + return NO; + } + + // Start the muxer and wait + [_muxer work]; + + [_muxer release], _muxer = nil; + [_importers removeAllObjects]; + + // Generate previews images for chapters + if ([[attributes valueForKey:MP42OrganizeAlternateGroups] boolValue]) + [self organizeAlternateGroups]; + + // Update modified tracks properties + updateMoovDuration(_fileHandle); + for (MP42Track *track in _tracks) { + if (track.isEdited) { + noErr = [track writeToFile:_fileHandle error:outError]; + if (!noErr) + break; + } + } + + // Update metadata + if (_metadata.isEdited) + [_metadata writeMetadataWithFileHandle:_fileHandle]; + + // Close the mp4 file handle + if (!MP4Close(_fileHandle, 0)) { + if (outError) + *outError = MP42Error(@"File excedes 4 GB.", + @"The file is bigger than 4 GB, but it was created with 32bit data chunk offset.\nSelect 64bit data chunk offset in the save panel.", + 100); + return NO; + } + + // Generate previews images for chapters + if ([[attributes valueForKey:MP42CreateChaptersPreviewTrack] boolValue] && [_tracks count]) + [self createChaptersPreview]; + + if ([_delegate respondsToSelector:@selector(endSave:)]) + [_delegate performSelector:@selector(endSave:) withObject:self]; + + return noErr; +} + +- (void)cancel; +{ + _cancelled = YES; + [_muxer cancel]; +} + +- (void)progressStatus:(CGFloat)progress { + if ([_delegate respondsToSelector:@selector(progressStatus:)]) + [_delegate progressStatus:progress]; +} + +- (uint64_t)dataSize { + uint64_t estimation = 0; + for (MP42Track *track in _tracks) + estimation += track.dataLength; + + return estimation; +} + +- (void)removeMuxedTrack:(MP42Track *)track +{ + if (!_fileHandle) + return; + + // We have to handle a few special cases here. + if ([track isMemberOfClass:[MP42ChapterTrack class]]) { + MP4ChapterType err = MP4DeleteChapters(_fileHandle, MP4ChapterTypeAny, track.Id); + if (err == 0) + MP4DeleteTrack(_fileHandle, track.Id); + } + else + MP4DeleteTrack(_fileHandle, track.Id); + + updateTracksCount(_fileHandle); + updateMoovDuration(_fileHandle); +} + +- (void)organizeAlternateGroupsForMediaType:(NSString *)mediaType withGroupID:(NSUInteger)groupID +{ + NSArray *tracks = [self tracksWithMediaType:mediaType]; + BOOL enabled = NO; + + if (![tracks count]) + return; + + for (MP42Track *track in tracks) { + track.alternate_group = groupID; + + if (track.enabled && !enabled) + enabled = YES; + else if (track.enabled) + track.enabled = NO; + } + + if (!enabled) + [[tracks objectAtIndex:0] setEnabled:YES]; +} + +/** Create a set of alternate group the way iTunes and Apple devices want: + one alternate group for sound, one for subtitles, a disabled photo-jpeg track, + a disabled chapter track, and a video track with no alternate group */ +- (void)organizeAlternateGroups +{ + NSArray *typeToOrganize = @[MP42MediaTypeVideo, + MP42MediaTypeAudio, + MP42MediaTypeSubtitle]; + + for (int i = 0; i < [typeToOrganize count]; i++) { + [self organizeAlternateGroupsForMediaType:[typeToOrganize objectAtIndex:i] + withGroupID:i]; + } + + for (MP42Track *track in _tracks) { + if ([track isMemberOfClass:[MP42ChapterTrack class]]) + track.enabled = NO; + } +} + +- (NSArray *)generatePreviewImagesQTKitFromChapters:(NSArray *)chapters andFile:(NSURL *)file { + __block QTMovie * qtMovie; + + // QTMovie objects must always be create on the main thread. + NSDictionary *movieAttributes = @{QTMovieURLAttribute: file, + QTMovieAskUnresolvedDataRefsAttribute: @NO, + @"QTMovieOpenForPlaybackAttribute": @YES, + @"QTMovieOpenAsyncRequiredAttribute": @NO, + @"QTMovieOpenAsyncOKAttribute": @NO, + QTMovieApertureModeAttribute: QTMovieApertureModeClean}; + + if (dispatch_get_current_queue() != dispatch_get_main_queue()) { + dispatch_sync(dispatch_get_main_queue(), ^{ + qtMovie = [[QTMovie alloc] initWithAttributes:movieAttributes error:nil]; + }); + } + else + qtMovie = [[QTMovie alloc] initWithAttributes:movieAttributes error:nil]; + + if (!qtMovie) + return nil; + + for (QTTrack *qtTrack in [qtMovie tracksOfMediaType:@"sbtl"]) + [qtTrack setAttribute:@NO forKey:QTTrackEnabledAttribute]; + + NSDictionary *attributes = [NSDictionary dictionaryWithObject:QTMovieFrameImageTypeNSImage forKey:QTMovieFrameImageType]; + NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:[chapters count]]; + + for (SBTextSample *chapter in chapters) { + QTTime chapterTime = { + [chapter timestamp] + 1500, // Add a short offset, hopefully we will get a better image + 1000, // if there is a fade + 0 + }; + + NSImage *frame = [qtMovie frameImageAtTime:chapterTime withAttributes:attributes error:nil]; + + if (images) + [images addObject:frame]; + } + + // Release the movie, we don't want to keep it open while we are writing in it using another library. + // I am not sure if it is safe to release a QTMovie from a background thread, let's do it on the main just to be sure. + if (dispatch_get_current_queue() != dispatch_get_main_queue()) { + dispatch_sync(dispatch_get_main_queue(), ^{ + [qtMovie release]; + }); + } + else + [qtMovie release]; + + return [images autorelease]; +} + +- (NSArray *)generatePreviewImagesAVFoundationFromChapters:(NSArray *)chapters andFile:(NSURL *)file { + NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:[chapters count]]; + + // If we are on 10.7, use the AVFoundation path +#if __MAC_OS_X_VERSION_MAX_ALLOWED > 1060 + AVAsset *asset = [AVAsset assetWithURL:file]; + + if ([asset tracksWithMediaCharacteristic:AVMediaCharacteristicVisual]) { + AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset]; + generator.appliesPreferredTrackTransform = YES; + generator.apertureMode = AVAssetImageGeneratorApertureModeCleanAperture; + generator.requestedTimeToleranceBefore = kCMTimeZero; + generator.requestedTimeToleranceAfter = kCMTimeZero; + + for (SBTextSample * chapter in chapters) { + CMTime time = CMTimeMake([chapter timestamp] + 1800, 1000); + CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:NULL]; + if (imgRef) { + NSSize size = NSMakeSize(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef)); + NSImage *frame = [[NSImage alloc] initWithCGImage:imgRef size:size]; + + [images addObject:frame]; + [frame release]; + } + + CGImageRelease(imgRef); + } + } +#endif + + return [images autorelease]; +} + +- (BOOL)createChaptersPreview { + NSInteger decodable = 1; + MP42ChapterTrack *chapterTrack = nil; + MP42VideoTrack *refTrack = nil; + MP4TrackId jpegTrack = 0; + + for (MP42Track *track in _tracks) { + if ([track isMemberOfClass:[MP42ChapterTrack class]] && !chapterTrack) + chapterTrack = (MP42ChapterTrack *)track; + + if ([track isMemberOfClass:[MP42VideoTrack class]] && + ![track.format isEqualToString:MP42VideoFormatJPEG] + && !refTrack) + refTrack = (MP42VideoTrack *)track; + + if ([track.format isEqualToString:MP42VideoFormatJPEG] && !jpegTrack) + jpegTrack = track.Id; + + if ([track.format isEqualToString:MP42VideoFormatH264]) + if ((((MP42VideoTrack *)track).origProfile) == 110) + decodable = 0; + } + + if (!refTrack) + refTrack = [_tracks objectAtIndex:0]; + + if (chapterTrack && !jpegTrack && decodable) { + @autoreleasepool { + NSArray *images = nil; + + // If we are on 10.7 or later, use AVFoundation, else QTKit + if (NSClassFromString(@"AVAsset")) { + images = [self generatePreviewImagesAVFoundationFromChapters:[chapterTrack chapters] andFile:_fileURL]; + } else { + images = [self generatePreviewImagesQTKitFromChapters:[chapterTrack chapters] andFile:_fileURL]; + } + + // If we haven't got any images, return. + if (![images count]) + return NO; + + // Reopen the mp4v2 fileHandle + _fileHandle = MP4Modify([[_fileURL path] UTF8String], 0); + if (_fileHandle == MP4_INVALID_FILE_HANDLE) + return NO; + + CGFloat maxWidth = 640; + NSSize imageSize = [[images objectAtIndex:0] size]; + if (imageSize.width > maxWidth) { + imageSize.height = maxWidth / imageSize.width * imageSize.height; + imageSize.width = maxWidth; + } + NSRect rect = NSMakeRect(0.0, 0.0, imageSize.width, imageSize.height); + + jpegTrack = MP4AddJpegVideoTrack(_fileHandle, MP4GetTrackTimeScale(_fileHandle, [chapterTrack Id]), + MP4_INVALID_DURATION, imageSize.width, imageSize.height); + + MP4SetTrackLanguage(_fileHandle, jpegTrack, lang_for_english([refTrack.language UTF8String])->iso639_2); + MP4SetTrackIntegerProperty(_fileHandle, jpegTrack, "tkhd.layer", 1); + MP4SetTrackDisabled(_fileHandle, jpegTrack); + + NSUInteger idx = 0; + MP4Duration duration = 0; + + for (SBTextSample *chapterT in [chapterTrack chapters]) { + duration = MP4GetSampleDuration(_fileHandle, chapterTrack.Id, idx + 1); + + // Scale the image. + NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL + pixelsWide:rect.size.width + pixelsHigh:rect.size.height + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSCalibratedRGBColorSpace + bitmapFormat:NSAlphaFirstBitmapFormat + bytesPerRow:0 + bitsPerPixel:32]; + [NSGraphicsContext saveGraphicsState]; + [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap]]; + + [[NSColor blackColor] set]; + NSRectFill(rect); + + if (idx < [images count]) + [[images objectAtIndex:idx] drawInRect:rect fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0]; + + [NSGraphicsContext restoreGraphicsState]; + + NSData *data = [bitmap representationUsingType:NSJPEGFileType properties:nil]; + [bitmap release]; + + MP4WriteSample(_fileHandle, + jpegTrack, + [data bytes], + [data length], + duration, + 0, + true); + idx++; + } + + MP4RemoveAllTrackReferences(_fileHandle, "tref.chap", refTrack.Id); + MP4AddTrackReference(_fileHandle, "tref.chap", chapterTrack.Id, refTrack.Id); + MP4AddTrackReference(_fileHandle, "tref.chap", jpegTrack, refTrack.Id); + copyTrackEditLists(_fileHandle, chapterTrack.Id, jpegTrack); + + MP4Close(_fileHandle, 0); + } + + return YES; + } + else if (chapterTrack && jpegTrack) { + // We already have all the tracks, so hook them up. + _fileHandle = MP4Modify([[_fileURL path] UTF8String], 0); + if (_fileHandle == MP4_INVALID_FILE_HANDLE) + return NO; + + MP4RemoveAllTrackReferences(_fileHandle, "tref.chap", refTrack.Id); + MP4AddTrackReference(_fileHandle, "tref.chap", chapterTrack.Id, refTrack.Id); + MP4AddTrackReference(_fileHandle, "tref.chap", jpegTrack, refTrack.Id); + MP4Close(_fileHandle, 0); + } + + return NO; +} + +@synthesize delegate = _delegate; +@synthesize URL = _fileURL; +@synthesize tracks = _tracks; +@synthesize metadata = _metadata; +@synthesize hasFileRepresentation = _hasFileRepresentation; + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [coder encodeInt:2 forKey:@"MP42FileVersion"]; + +#ifdef SB_SANDBOX + if ([fileURL respondsToSelector:@selector(startAccessingSecurityScopedResource)]) { + NSData *bookmarkData = nil; + NSError *error = nil; + bookmarkData = [fileURL bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope + includingResourceValuesForKeys:nil + relativeToURL:nil // Make it app-scoped + error:&error]; + if (error) { + NSLog(@"Error creating bookmark for URL (%@): %@", fileURL, error); + } + + [coder encodeObject:bookmarkData forKey:@"bookmark"]; + + } + else { + [coder encodeObject:fileURL forKey:@"fileUrl"]; + } +#else + [coder encodeObject:_fileURL forKey:@"fileUrl"]; +#endif + + [coder encodeObject:_tracksToBeDeleted forKey:@"tracksToBeDeleted"]; + [coder encodeBool:_hasFileRepresentation forKey:@"hasFileRepresentation"]; + + [coder encodeObject:_tracks forKey:@"tracks"]; + [coder encodeObject:_metadata forKey:@"metadata"]; +} + +- (id)initWithCoder:(NSCoder *)decoder +{ + self = [super init]; + + NSData *bookmarkData = [decoder decodeObjectForKey:@"bookmark"]; + if (bookmarkData) { + BOOL bookmarkDataIsStale; + NSError *error; + _fileURL = [[NSURL + URLByResolvingBookmarkData:bookmarkData + options:NSURLBookmarkResolutionWithSecurityScope + relativeToURL:nil + bookmarkDataIsStale:&bookmarkDataIsStale + error:&error] retain]; + } + else { + _fileURL = [[decoder decodeObjectForKey:@"fileUrl"] retain]; + } + + _tracksToBeDeleted = [[decoder decodeObjectForKey:@"tracksToBeDeleted"] retain]; + + _hasFileRepresentation = [decoder decodeBoolForKey:@"hasFileRepresentation"]; + + _tracks = [[decoder decodeObjectForKey:@"tracks"] retain]; + _metadata = [[decoder decodeObjectForKey:@"metadata"] retain]; + + return self; +} + +- (void)dealloc +{ + [_fileURL release]; + [_tracks release]; + [_importers release]; + [_tracksToBeDeleted release]; + [_metadata release]; + + [super dealloc]; +} + +@end diff --git a/MP42/MP42FileImporter.h b/MP42/MP42FileImporter.h new file mode 100644 index 0000000..92dfd6c --- /dev/null +++ b/MP42/MP42FileImporter.h @@ -0,0 +1,65 @@ +// +// MP42FileImporter.h +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import +#import + +#import "MP42Sample.h" +#import "MP42Utilities.h" + +#import "mp4v2.h" + +@class MP42Sample; +@class MP42Metadata; +@class MP42Track; + +@interface MP42FileImporter : NSObject { + NSURL *_fileURL; + + NSInteger _chapterId; + MP42Metadata *_metadata; + + NSMutableArray *_tracksArray; + NSMutableArray *_inputTracks; + NSMutableArray *_outputsTracks; + NSThread *_demuxerThread; + + CGFloat _progress; + int32_t _cancelled; + int32_t _done; + dispatch_semaphore_t _doneSem; +} + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError; + +- (BOOL)containsTrack:(MP42Track*)track; +- (MP42Track *)inputTrackWithTrackID:(MP4TrackId)trackId; + +- (NSUInteger)timescaleForTrack:(MP42Track *)track; +- (NSSize)sizeForTrack:(MP42Track *)track; +- (NSData *)magicCookieForTrack:(MP42Track *)track; +- (AudioStreamBasicDescription)audioDescriptionForTrack:(MP42Track *)track; + +- (void)setActiveTrack:(MP42Track *)track; + +- (void)startReading; +- (void)cancelReading; + +- (void)enqueue:(MP42SampleBuffer *)sample; + +- (CGFloat)progress; + +- (BOOL)done; +- (void)setDone:(BOOL)status; + +- (BOOL)cleanUp:(MP4FileHandle) fileHandle; + +@property(readwrite, retain) MP42Metadata *metadata; +@property(readonly) NSMutableArray *tracks; + +@end diff --git a/MP42/MP42FileImporter.m b/MP42/MP42FileImporter.m new file mode 100644 index 0000000..23b8e77 --- /dev/null +++ b/MP42/MP42FileImporter.m @@ -0,0 +1,221 @@ +// +// MP42FileImporter.m +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import "MP42FileImporter.h" +#import "MP42MkvImporter.h" +#import "MP42Mp4Importer.h" +#import "MP42SrtImporter.h" +#import "MP42CCImporter.h" +#import "MP42AC3Importer.h" +#import "MP42AACImporter.h" +#import "MP42H264Importer.h" +#import "MP42VobSubImporter.h" +#import "MP42Track.h" +#import "MP42Fifo.h" + +#if !__LP64__ +#import "MP42QTImporter.h" +#endif + +#import "MP42AVFImporter.h" + +#include "MP42AudioConverter.h" + +@implementation MP42FileImporter + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError; +{ + [self release]; + self = nil; + if ([[fileURL pathExtension] caseInsensitiveCompare: @"mkv"] == NSOrderedSame || + [[fileURL pathExtension] caseInsensitiveCompare: @"mka"] == NSOrderedSame || + [[fileURL pathExtension] caseInsensitiveCompare: @"mks"] == NSOrderedSame) + self = [MP42MkvImporter alloc]; + else if ([[fileURL pathExtension] caseInsensitiveCompare: @"mp4"] == NSOrderedSame || + [[fileURL pathExtension] caseInsensitiveCompare: @"m4v"] == NSOrderedSame || + [[fileURL pathExtension] caseInsensitiveCompare: @"m4a"] == NSOrderedSame) + self = [MP42Mp4Importer alloc]; + else if ([[fileURL pathExtension] caseInsensitiveCompare: @"srt"] == NSOrderedSame) + self = [MP42SrtImporter alloc]; + else if ([[fileURL pathExtension] caseInsensitiveCompare: @"scc"] == NSOrderedSame) + self = [MP42CCImporter alloc]; + else if ([[fileURL pathExtension] caseInsensitiveCompare: @"ac3"] == NSOrderedSame) + self = [MP42AC3Importer alloc]; + else if ([[fileURL pathExtension] caseInsensitiveCompare: @"aac"] == NSOrderedSame) + self = [MP42AACImporter alloc]; + else if ([[fileURL pathExtension] caseInsensitiveCompare: @"264"] == NSOrderedSame || + [[fileURL pathExtension] caseInsensitiveCompare: @"h264"] == NSOrderedSame) + self = [MP42H264Importer alloc]; + else if ([[fileURL pathExtension] caseInsensitiveCompare: @"idx"] == NSOrderedSame || + [[fileURL pathExtension] caseInsensitiveCompare: @"idx"] == NSOrderedSame) + self = [MP42VobSubImporter alloc]; +#if !__LP64__ + else if ([[fileURL pathExtension] caseInsensitiveCompare: @"mov"] == NSOrderedSame) { + self = [MP42QTImporter alloc]; + } +#endif + // If we are on 10.7 or later, use the AVFoundation path + else if (NSClassFromString(@"AVAsset")) { + if ([[fileURL pathExtension] caseInsensitiveCompare: @"m2ts"] == NSOrderedSame || + [[fileURL pathExtension] caseInsensitiveCompare: @"mts"] == NSOrderedSame ) { + self = [MP42AVFImporter alloc]; + } + } + + if (self) { + self = [self initWithURL:fileURL error:outError]; + + if (self) { + for (MP42Track *track in _tracksArray) + track.muxer_helper->importer = self; + } + } + + return self; +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + return 0; +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + return NSMakeSize(0,0); +} + +- (NSData *)magicCookieForTrack:(MP42Track *)track +{ + return nil; +} + +- (AudioStreamBasicDescription)audioDescriptionForTrack:(MP42Track *)track +{ + AudioStreamBasicDescription desc = {0,0,0,0,0,0,0,0,0}; + return desc; +} + +- (void)setActiveTrack:(MP42Track *)track { + if (!_inputTracks) { + _inputTracks = [[NSMutableArray alloc] init]; + _outputsTracks = [[NSMutableArray alloc] init]; + } + + BOOL alreadyAdded = NO; + for (MP42Track *inputTrack in _inputTracks) + if (inputTrack.sourceId == track.sourceId) + alreadyAdded = YES; + + if (!alreadyAdded) + [_inputTracks addObject:track]; + + [_outputsTracks addObject:track]; +} + +- (void)startReading +{ + for (MP42Track *track in _outputsTracks) + track.muxer_helper->fifo = [[MP42Fifo alloc] init]; + + _doneSem = dispatch_semaphore_create(0); +} + +- (void)cancelReading +{ + OSAtomicIncrement32(&_cancelled); + + for (MP42Track *track in _outputsTracks) { + [track.muxer_helper->fifo cancel]; + } + + // wait until the demuxer thread exits + dispatch_semaphore_wait(_doneSem, DISPATCH_TIME_FOREVER); + + // stop all the related converters + for (MP42Track *track in _outputsTracks) { + [track.muxer_helper->converter cancel]; + } +} + +- (void)enqueue:(MP42SampleBuffer *)sample { + for (MP42Track *track in _outputsTracks) { + if (track.sourceId == sample->trackId) { + if (track.muxer_helper->converter) { + [track.muxer_helper->converter addSample:sample]; + } else { + [track.muxer_helper->fifo enqueue:sample]; + } + } + } +} + +- (BOOL)done +{ + return _done; +} + +- (void)setDone:(BOOL)status { + OSAtomicIncrement32(&_done); + dispatch_semaphore_signal(_doneSem); +} + +- (CGFloat)progress +{ + return _progress; +} + +- (BOOL)cleanUp:(MP4FileHandle)fileHandle +{ + return NO; +} + +- (BOOL)containsTrack:(MP42Track *)track +{ + return [_tracksArray containsObject:track]; +} + +- (MP42Track *)inputTrackWithTrackID:(MP4TrackId)trackId +{ + for (MP42Track *track in _inputTracks) { + if (track.sourceId == trackId) { + return track;; + } + } + + return nil; +} + +- (void)dealloc +{ + for (MP42Track *track in _inputTracks) { + [track.muxer_helper->demuxer_context release]; + } + + for (MP42Track *track in _outputsTracks) { + [track.muxer_helper->fifo release]; + [track.muxer_helper->converter release]; + } + + [_metadata release], _metadata = nil; + [_tracksArray release], _tracksArray = nil; + [_inputTracks release], _inputTracks = nil; + [_outputsTracks release], _outputsTracks = nil; + + [_fileURL release], _fileURL = nil; + [_demuxerThread release], _demuxerThread = nil; + + if (_doneSem) + dispatch_release(_doneSem); + + [super dealloc]; +} + +@synthesize metadata = _metadata; +@synthesize tracks = _tracksArray; + +@end diff --git a/MP42/MP42H264Importer.h b/MP42/MP42H264Importer.h new file mode 100644 index 0000000..9c832a0 --- /dev/null +++ b/MP42/MP42H264Importer.h @@ -0,0 +1,45 @@ +// +// MP42H264FileImporter.h +// Subler +// +// Created by Damiano Galassi on 07/12/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import +#import "MP42FileImporter.h" + +typedef struct framerate_t { + uint32_t code; + uint32_t timescale; + uint32_t duration; +} framerate_t; +typedef struct + +{ + struct + { + int size_min; + int next; + int cnt; + int idx[17]; + int poc[17]; + } dpb; + + int cnt; + int cnt_max; + int *frame; +} h264_dpb_t; + +@interface MP42H264Importer : MP42FileImporter { + FILE* inFile; + int64_t _size; + + NSData *avcC; + uint32_t timescale; + uint32_t mp4FrameDuration; + MP4SampleId samplesWritten; + h264_dpb_t h264_dpb; +} + +@end \ No newline at end of file diff --git a/MP42/MP42H264Importer.mm b/MP42/MP42H264Importer.mm new file mode 100644 index 0000000..a4044b0 --- /dev/null +++ b/MP42/MP42H264Importer.mm @@ -0,0 +1,1651 @@ +// +// MP42H264FileImporter.m +// Subler +// +// Created by Damiano Galassi on 07/12/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import "MP42H264Importer.h" +#import "SBLanguages.h" +#import "MP42File.h" +#include + +//#define DEBUG_H264 + +static const framerate_t framerates[] = +{ { 2398, 24000, 1001 }, + { 24, 600, 25 }, + { 25, 600, 24 }, + { 2997, 30000, 1001 }, + { 30, 600, 20 }, + { 50, 600, 12 }, + { 5994, 60000, 1001 }, + { 60, 600, 10 }, + { 0, 24000, 1001 } }; + +static const framerate_t framerates_thousand[] = +{ { 2398, 24000, 1001 }, + { 2400, 600, 25 }, + { 2500, 600, 24 }, + { 2997, 30000, 1001 }, + { 3000, 600, 20 }, + { 5000, 600, 12 }, + { 5994, 60000, 1001 }, + { 6000, 600, 10 }, + { 0, 24000, 1001 } }; + +typedef struct h264_decode_t { + uint8_t profile; + uint8_t level; + uint32_t chroma_format_idc; + uint8_t residual_colour_transform_flag; + uint32_t bit_depth_luma_minus8; + uint32_t bit_depth_chroma_minus8; + uint8_t qpprime_y_zero_transform_bypass_flag; + uint8_t seq_scaling_matrix_present_flag; + uint32_t log2_max_frame_num_minus4; + uint32_t log2_max_pic_order_cnt_lsb_minus4; + uint32_t pic_order_cnt_type; + uint8_t frame_mbs_only_flag; + uint8_t mb_adaptive_frame_field_flag; + uint8_t direct_8x8_inference_flag; + uint32_t frame_crop_left_offset; + uint32_t frame_crop_right_offset; + uint32_t frame_crop_top_offset; + uint32_t frame_crop_bottom_offset; + uint8_t aspect_ratio_info_present_flag; + uint8_t aspect_ratio_idc; + uint8_t pic_order_present_flag; + uint8_t delta_pic_order_always_zero_flag; + int32_t offset_for_non_ref_pic; + int32_t offset_for_top_to_bottom_field; + uint32_t pic_order_cnt_cycle_length; + int16_t offset_for_ref_frame[256]; + + uint8_t nal_ref_idc; + uint8_t nal_unit_type; + + uint8_t field_pic_flag; + uint8_t bottom_field_flag; + uint32_t frame_num; + uint32_t idr_pic_id; + uint32_t pic_order_cnt_lsb; + int32_t delta_pic_order_cnt_bottom; + int32_t delta_pic_order_cnt[2]; + + uint32_t pic_width, pic_height; + uint32_t sar_width, sar_height; + uint32_t slice_type; + + /* POC state */ + int32_t pic_order_cnt; /* can be < 0 */ + + uint32_t pic_order_cnt_msb; + uint32_t pic_order_cnt_msb_prev; + uint32_t pic_order_cnt_lsb_prev; + uint32_t frame_num_prev; + int32_t frame_num_offset; + int32_t frame_num_offset_prev; + + uint8_t NalHrdBpPresentFlag; + uint8_t VclHrdBpPresentFlag; + uint8_t CpbDpbDelaysPresentFlag; + uint8_t pic_struct_present_flag; + uint8_t cpb_removal_delay_length_minus1; + uint8_t dpb_output_delay_length_minus1; + uint8_t time_offset_length; + uint32_t cpb_cnt_minus1; + uint8_t initial_cpb_removal_delay_length_minus1; +} h264_decode_t; + +typedef struct nal_reader_t { + FILE *ifile; + int pipeFD; + int usePipe; + uint8_t *buffer; + uint32_t buffer_on; + uint32_t buffer_size; + uint32_t buffer_size_max; +} nal_reader_t; + +#define H264_START_CODE 0x000001 +#define H264_PREVENT_3_BYTE 0x000003 + +#define H264_PROFILE_BASELINE 66 +#define H264_PROFILE_MAIN 77 +#define H264_PROFILE_EXTENDED 88 + +#define H264_NAL_TYPE_NON_IDR_SLICE 1 +#define H264_NAL_TYPE_DP_A_SLICE 2 +#define H264_NAL_TYPE_DP_B_SLICE 3 +#define H264_NAL_TYPE_DP_C_SLICE 0x4 +#define H264_NAL_TYPE_IDR_SLICE 0x5 +#define H264_NAL_TYPE_SEI 0x6 +#define H264_NAL_TYPE_SEQ_PARAM 0x7 +#define H264_NAL_TYPE_PIC_PARAM 0x8 +#define H264_NAL_TYPE_ACCESS_UNIT 0x9 +#define H264_NAL_TYPE_END_OF_SEQ 0xa +#define H264_NAL_TYPE_END_OF_STREAM 0xb +#define H264_NAL_TYPE_FILLER_DATA 0xc +#define H264_NAL_TYPE_SEQ_EXTENSION 0xd + +#define H264_TYPE_P 0 +#define H264_TYPE_B 1 +#define H264_TYPE_I 2 +#define H264_TYPE_SP 3 +#define H264_TYPE_SI 4 +#define H264_TYPE2_P 5 +#define H264_TYPE2_B 6 +#define H264_TYPE2_I 7 +#define H264_TYPE2_SP 8 +#define H264_TYPE2_SI 9 + +#define H264_TYPE_IS_P(t) ((t) == H264_TYPE_P || (t) == H264_TYPE2_P) +#define H264_TYPE_IS_B(t) ((t) == H264_TYPE_B || (t) == H264_TYPE2_B) +#define H264_TYPE_IS_I(t) ((t) == H264_TYPE_I || (t) == H264_TYPE2_I) +#define H264_TYPE_IS_SP(t) ((t) == H264_TYPE_SP || (t) == H264_TYPE2_SP) +#define H264_TYPE_IS_SI(t) ((t) == H264_TYPE_SI || (t) == H264_TYPE2_SI) + +#define HAVE_SLICE_I 0x1 +#define HAVE_SLICE_P 0x2 +#define HAVE_SLICE_B 0x4 +#define HAVE_SLICE_SI 0x8 +#define HAVE_SLICE_SP 0x10 +#define HAVE_ALL_SLICES 0x1f +#define HAVE_ALL_BUT_B_SLICES 0x1b + +static uint8_t exp_golomb_bits[256] = { + 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, +}; + +static const char *ProgName = "Subler"; +static int Verbosity = 0; + +#include "mp4v2.h" +#include +#include /* isdigit, isprint, isspace */ +#include +#include +#include +#include +#include +#include +#include "mpeg4ip_bitstream.h" + +uint32_t h264_ue (CBitstream *bs) +{ + uint32_t bits, read; + int bits_left; + uint8_t coded; + bool done = false; + uint32_t temp; + bits = 0; + // we want to read 8 bits at a time - if we don't have 8 bits, + // read what's left, and shift. The exp_golomb_bits calc remains the + // same. + while (done == false) { + bits_left = bs->bits_remain(); + if (bits_left < 8) { + read = bs->PeekBits(bits_left) << (8 - bits_left); + done = true; + } else { + read = bs->PeekBits(8); + if (read == 0) { + (void)bs->GetBits(8); + bits += 8; + } else { + done = true; + } + } + } + coded = exp_golomb_bits[read]; + temp = bs->GetBits(coded); + bits += coded; + + // printf("ue - bits %d\n", bits); + return bs->GetBits(bits + 1) - 1; +} + +int32_t h264_se (CBitstream *bs) +{ + uint32_t ret; + ret = h264_ue(bs); + if ((ret & 0x1) == 0) { + ret >>= 1; + int32_t temp = 0 - ret; + return temp; + } + return (ret + 1) >> 1; +} + +static void h264_decode_annexb( uint8_t *dst, int *dstlen, + const uint8_t *src, const int srclen ) +{ + uint8_t *dst_sav = dst; + const uint8_t *end = &src[srclen]; + + while (src < end) + { + if (src < end - 3 && src[0] == 0x00 && src[1] == 0x00 && + src[2] == 0x03) + { + *dst++ = 0x00; + *dst++ = 0x00; + + src += 3; + continue; + } + *dst++ = *src++; + } + + *dstlen = dst - dst_sav; +} + +extern "C" bool h264_is_start_code (const uint8_t *pBuf) +{ + if (pBuf[0] == 0 && + pBuf[1] == 0 && + ((pBuf[2] == 1) || + ((pBuf[2] == 0) && pBuf[3] == 1))) { + return true; + } + return false; +} + +extern "C" uint32_t h264_find_next_start_code (const uint8_t *pBuf, + uint32_t bufLen) +{ + uint32_t val, temp; + uint32_t offset; + + offset = 0; + if (pBuf[0] == 0 && + pBuf[1] == 0 && + ((pBuf[2] == 1) || + ((pBuf[2] == 0) && pBuf[3] == 1))) { + pBuf += 3; + offset = 3; + } + val = 0xffffffff; + while (offset < bufLen - 3) { + val <<= 8; + temp = val & 0xff000000; + val &= 0x00ffffff; + val |= *pBuf++; + offset++; + if (val == H264_START_CODE) { + if (temp == 0) return offset - 4; + return offset - 3; + } + } + return 0; +} + +extern "C" uint8_t h264_nal_unit_type (const uint8_t *buffer) +{ + uint32_t offset; + if (buffer[2] == 1) offset = 3; + else offset = 4; + return buffer[offset] & 0x1f; +} + +extern "C" int h264_nal_unit_type_is_slice (const uint8_t type) +{ + if (type >= H264_NAL_TYPE_NON_IDR_SLICE && + type <= H264_NAL_TYPE_IDR_SLICE) { + return true; + } + return false; +} + +/* + * determine if the slice we decoded is a sync point + */ +extern "C" bool h264_slice_is_idr (h264_decode_t *dec) +{ + if (dec->nal_unit_type != H264_NAL_TYPE_IDR_SLICE) + return false; + if (H264_TYPE_IS_I(dec->slice_type)) return true; + if (H264_TYPE_IS_SI(dec->slice_type)) return true; + return false; +} + +extern "C" uint8_t h264_nal_ref_idc (const uint8_t *buffer) +{ + uint32_t offset; + if (buffer[2] == 1) offset = 3; + else offset = 4; + return (buffer[offset] >> 5) & 0x3; +} + +static void scaling_list (uint sizeOfScalingList, CBitstream *bs) +{ + uint lastScale = 8, nextScale = 8; + uint j; + + for (j = 0; j < sizeOfScalingList; j++) { + if (nextScale != 0) { + int deltaScale = h264_se(bs); + nextScale = (lastScale + deltaScale + 256) % 256; + } + if (nextScale == 0) { + lastScale = lastScale; + } else { + lastScale = nextScale; + } + } +} + +extern "C" void h264_hrd_parameters (h264_decode_t *dec, CBitstream *bs) +{ + uint32_t cpb_cnt; + dec->cpb_cnt_minus1 = cpb_cnt = h264_ue(bs); + uint32_t temp; + printf(" cpb_cnt_minus1: %u\n", cpb_cnt); + printf(" bit_rate_scale: %u\n", bs->GetBits(4)); + printf(" cpb_size_scale: %u\n", bs->GetBits(4)); + for (uint32_t ix = 0; ix <= cpb_cnt; ix++) { + printf(" bit_rate_value_minus1[%u]: %u\n", ix, h264_ue(bs)); + printf(" cpb_size_value_minus1[%u]: %u\n", ix, h264_ue(bs)); + printf(" cbr_flag[%u]: %u\n", ix, bs->GetBits(1)); + } + temp = dec->initial_cpb_removal_delay_length_minus1 = bs->GetBits(5); + printf(" initial_cpb_removal_delay_length_minus1: %u\n", temp); + + dec->cpb_removal_delay_length_minus1 = temp = bs->GetBits(5); + printf(" cpb_removal_delay_length_minus1: %u\n", temp); + dec->dpb_output_delay_length_minus1 = temp = bs->GetBits(5); + printf(" dpb_output_delay_length_minus1: %u\n", temp); + dec->time_offset_length = temp = bs->GetBits(5); + printf(" time_offset_length: %u\n", temp); +} + +extern "C" void h264_vui_parameters (h264_decode_t *dec, CBitstream *bs) +{ + //uint32_t temp; + dec->aspect_ratio_info_present_flag = bs->GetBits(1); + if (dec->aspect_ratio_info_present_flag) { + dec->aspect_ratio_idc = bs->GetBits(8); + if (dec->aspect_ratio_idc == 0xff) { // extended_SAR + dec->sar_width = bs->GetBits(16); + dec->sar_height = bs->GetBits(16); + } + } + +#if 0 + temp = bs->GetBits(1); + printf(" overscan_info_present_flag: %u\n", temp); + if (temp) { + printf(" overscan_appropriate_flag: %u\n", bs->GetBits(1)); + } + temp = bs->GetBits(1); + printf(" video_signal_info_present_flag: %u\n", temp); + if (temp) { + printf(" video_format: %u\n", bs->GetBits(3)); + printf(" video_full_range_flag: %u\n", bs->GetBits(1)); + temp = bs->GetBits(1); + printf(" colour_description_present_flag: %u\n", temp); + if (temp) { + printf(" colour_primaries: %u\n", bs->GetBits(8)); + printf(" transfer_characteristics: %u\n", bs->GetBits(8)); + printf(" matrix_coefficients: %u\n", bs->GetBits(8)); + } + } + + temp = bs->GetBits(1); + printf(" chroma_loc_info_present_flag: %u\n", temp); + if (temp) { + printf(" chroma_sample_loc_type_top_field: %u\n", h264_ue(bs)); + printf(" chroma_sample_loc_type_bottom_field: %u\n", h264_ue(bs)); + } + temp = bs->GetBits(1); + printf(" timing_info_present_flag: %u\n", temp); + if (temp) { + printf(" num_units_in_tick: %u\n", bs->GetBits(32)); + printf(" time_scale: %u\n", bs->GetBits(32)); + printf(" fixed_frame_scale: %u\n", bs->GetBits(1)); + } + temp = bs->GetBits(1); + printf(" nal_hrd_parameters_present_flag: %u\n", temp); + if (temp) { + dec->NalHrdBpPresentFlag = 1; + dec->CpbDpbDelaysPresentFlag = 1; + h264_hrd_parameters(dec, bs); + } + uint32_t temp2; + + temp2 = bs->GetBits(1); + printf(" vcl_hrd_parameters_present_flag: %u\n", temp2); + if (temp2) { + dec->VclHrdBpPresentFlag = 1; + dec->CpbDpbDelaysPresentFlag = 1; + h264_hrd_parameters(dec, bs); + } + if (temp || temp2) { + printf(" low_delay_hrd_flag: %u\n", bs->GetBits(1)); + } + dec->pic_struct_present_flag = temp = bs->GetBits(1); + printf(" pic_struct_present_flag: %u\n", temp); + temp = bs->GetBits(1); + if (temp) { + printf(" motion_vectors_over_pic_boundaries_flag: %u\n", bs->GetBits(1)); + printf(" max_bytes_per_pic_denom: %u\n", h264_ue(bs)); + printf(" max_bits_per_mb_denom: %u\n", h264_ue(bs)); + printf(" log2_max_mv_length_horizontal: %u\n", h264_ue(bs)); + printf(" log2_max_mv_length_vertical: %u\n", h264_ue(bs)); + printf(" num_reorder_frames: %u\n", h264_ue(bs)); + printf(" max_dec_frame_buffering: %u\n", h264_ue(bs)); + } +#endif +} + +int h264_read_seq_info (const uint8_t *buffer, + uint32_t buflen, + h264_decode_t *dec) +{ + CBitstream bs; + uint32_t header; + uint8_t tmp[2048]; /* Should be enough for all SPS (we have at worst 13 bytes and 496 se/ue in frext) */ + int tmp_len; + uint32_t dummy; + + if (buffer[2] == 1) header = 4; + else header = 5; + + h264_decode_annexb( tmp, &tmp_len, buffer + header, MIN(buflen-header,2048) ); + bs.init(tmp, tmp_len * 8); + + //bs.set_verbose(true); + try { + dec->profile = bs.GetBits(8); + dummy = bs.GetBits(1 + 1 + 1 + 1 + 4); + dec->level = bs.GetBits(8); + (void)h264_ue(&bs); // seq_parameter_set_id + if (dec->profile == 100 || dec->profile == 110 || + dec->profile == 122 || dec->profile == 144) { + dec->chroma_format_idc = h264_ue(&bs); + if (dec->chroma_format_idc == 3) { + dec->residual_colour_transform_flag = bs.GetBits(1); + } + dec->bit_depth_luma_minus8 = h264_ue(&bs); + dec->bit_depth_chroma_minus8 = h264_ue(&bs); + dec->qpprime_y_zero_transform_bypass_flag = bs.GetBits(1); + dec->seq_scaling_matrix_present_flag = bs.GetBits(1); + if (dec->seq_scaling_matrix_present_flag) { + for (uint ix = 0; ix < 8; ix++) { + if (bs.GetBits(1)) { + scaling_list(ix < 6 ? 16 : 64, &bs); + } + } + } + } + dec->log2_max_frame_num_minus4 = h264_ue(&bs); + dec->pic_order_cnt_type = h264_ue(&bs); + if (dec->pic_order_cnt_type == 0) { + dec->log2_max_pic_order_cnt_lsb_minus4 = h264_ue(&bs); + } else if (dec->pic_order_cnt_type == 1) { + dec->delta_pic_order_always_zero_flag = bs.GetBits(1); + dec->offset_for_non_ref_pic = h264_se(&bs); // offset_for_non_ref_pic + dec->offset_for_top_to_bottom_field = h264_se(&bs); // offset_for_top_to_bottom_field + dec->pic_order_cnt_cycle_length = h264_ue(&bs); // poc_cycle_length + for (uint32_t ix = 0; ix < dec->pic_order_cnt_cycle_length; ix++) { + dec->offset_for_ref_frame[MIN(ix,255)] = h264_se(&bs); // offset for ref fram - + } + } + dummy = h264_ue(&bs); // num_ref_frames + dummy = bs.GetBits(1); // gaps_in_frame_num_value_allowed_flag + uint32_t PicWidthInMbs = h264_ue(&bs) + 1; + dec->pic_width = PicWidthInMbs * 16; + uint32_t PicHeightInMapUnits = h264_ue(&bs) + 1; + + dec->frame_mbs_only_flag = bs.GetBits(1); + dec->pic_height = + (2 - dec->frame_mbs_only_flag) * PicHeightInMapUnits * 16; + + if (!dec->frame_mbs_only_flag) { + dec->mb_adaptive_frame_field_flag = bs.GetBits(1); + } + dec->direct_8x8_inference_flag = bs.GetBits(1); + dummy = bs.GetBits(1); + if (dummy) { + dec->frame_crop_left_offset = h264_ue(&bs); + dec->frame_crop_right_offset = h264_ue(&bs); + dec->frame_crop_top_offset = h264_ue(&bs); + dec->frame_crop_bottom_offset = h264_ue(&bs); + + dec->pic_width -= 2*dec->frame_crop_right_offset; + if (dec->frame_mbs_only_flag) + dec->pic_height -= 2*dec->frame_crop_bottom_offset; + else + dec->pic_height -= 4*dec->frame_crop_bottom_offset; + } + dummy = bs.GetBits(1); + if (dummy) { + h264_vui_parameters(dec, &bs); + } + + } catch (...) { + return -1; + } + return 0; +} +extern "C" int h264_find_slice_type (const uint8_t *buffer, + uint32_t buflen, + uint8_t *slice_type, + bool noheader) +{ + uint32_t header; + uint32_t dummy; + if (noheader) header = 1; + else { + if (buffer[2] == 1) header = 4; + else header = 5; + } + CBitstream bs; + bs.init(buffer + header, (buflen - header) * 8); + try { + dummy = h264_ue(&bs); // first_mb_in_slice + *slice_type = h264_ue(&bs); // slice type + } catch (...) { + return -1; + } + return 0; +} + +extern "C" int h264_read_slice_info (const uint8_t *buffer, + uint32_t buflen, + h264_decode_t *dec) +{ + uint32_t header; + uint8_t tmp[512]; /* Enough for the begining of the slice header */ + int tmp_len; + uint32_t temp; + + if (buffer[2] == 1) header = 4; + else header = 5; + CBitstream bs; + + h264_decode_annexb( tmp, &tmp_len, buffer + header, MIN(buflen-header,512) ); + bs.init(tmp, tmp_len * 8); + try { + dec->field_pic_flag = 0; + dec->bottom_field_flag = 0; + dec->delta_pic_order_cnt[0] = 0; + dec->delta_pic_order_cnt[1] = 0; + temp = h264_ue(&bs); // first_mb_in_slice + dec->slice_type = h264_ue(&bs); // slice type + temp = h264_ue(&bs); // pic_parameter_set + dec->frame_num = bs.GetBits(dec->log2_max_frame_num_minus4 + 4); + if (!dec->frame_mbs_only_flag) { + dec->field_pic_flag = bs.GetBits(1); + if (dec->field_pic_flag) { + dec->bottom_field_flag = bs.GetBits(1); + } + } + if (dec->nal_unit_type == H264_NAL_TYPE_IDR_SLICE) { + dec->idr_pic_id = h264_ue(&bs); + } + switch (dec->pic_order_cnt_type) { + case 0: + dec->pic_order_cnt_lsb = bs.GetBits(dec->log2_max_pic_order_cnt_lsb_minus4 + 4); + if (dec->pic_order_present_flag && !dec->field_pic_flag) { + dec->delta_pic_order_cnt_bottom = h264_se(&bs); + } + break; + case 1: + if (!dec->delta_pic_order_always_zero_flag) { + dec->delta_pic_order_cnt[0] = h264_se(&bs); + } + if (dec->pic_order_present_flag && !dec->field_pic_flag) { + dec->delta_pic_order_cnt[1] = h264_se(&bs); + } + break; + } + + } catch (...) { + return -1; + } + return 0; +} + +static void h264_compute_poc( h264_decode_t *dec ) { + const int max_frame_num = 1 << (dec->log2_max_frame_num_minus4 + 4); + int field_poc[2] = {0,0}; + enum { + H264_PICTURE_FRAME, + H264_PICTURE_FIELD_TOP, + H264_PICTURE_FIELD_BOTTOM, + } pic_type; + + /* FIXME FIXME it doesn't handle the case where there is a MMCO == 5 + * (MMCO 5 "emulates" an idr) */ + + /* picture type */ + if (dec->frame_mbs_only_flag || !dec->field_pic_flag) + pic_type = H264_PICTURE_FRAME; + else if (dec->bottom_field_flag) + pic_type = H264_PICTURE_FIELD_BOTTOM; + else + pic_type = H264_PICTURE_FIELD_TOP; + + /* frame_num_offset */ + if (dec->nal_unit_type == H264_NAL_TYPE_IDR_SLICE) { + dec->pic_order_cnt_lsb_prev = 0; + dec->pic_order_cnt_msb_prev = 0; + dec->frame_num_offset = 0; + } else { + if (dec->frame_num < dec->frame_num_prev) + dec->frame_num_offset = dec->frame_num_offset_prev + max_frame_num; + else + dec->frame_num_offset = dec->frame_num_offset_prev; + } + + /* */ + if(dec->pic_order_cnt_type == 0) { + const unsigned int max_poc_lsb = 1 << (dec->log2_max_pic_order_cnt_lsb_minus4 + 4); + + if (dec->pic_order_cnt_lsb < dec->pic_order_cnt_lsb_prev && + dec->pic_order_cnt_lsb_prev - dec->pic_order_cnt_lsb >= max_poc_lsb / 2) + dec->pic_order_cnt_msb = dec->pic_order_cnt_msb_prev + max_poc_lsb; + else if (dec->pic_order_cnt_lsb > dec->pic_order_cnt_lsb_prev && + dec->pic_order_cnt_lsb - dec->pic_order_cnt_lsb_prev > max_poc_lsb / 2) + dec->pic_order_cnt_msb = dec->pic_order_cnt_msb_prev - max_poc_lsb; + else + dec->pic_order_cnt_msb = dec->pic_order_cnt_msb_prev; + + field_poc[0] = dec->pic_order_cnt_msb + dec->pic_order_cnt_lsb; + field_poc[1] = field_poc[0]; + if (pic_type == H264_PICTURE_FRAME) + field_poc[1] += dec->delta_pic_order_cnt_bottom; + + } else if (dec->pic_order_cnt_type == 1) { + int abs_frame_num, expected_delta_per_poc_cycle, expected_poc; + + if (dec->pic_order_cnt_cycle_length != 0) + abs_frame_num = dec->frame_num_offset + dec->frame_num; + else + abs_frame_num = 0; + + if (dec->nal_ref_idc == 0 && abs_frame_num > 0) + abs_frame_num--; + + expected_delta_per_poc_cycle = 0; + for (int i = 0; i < (int)dec->pic_order_cnt_cycle_length; i++ ) + expected_delta_per_poc_cycle += dec->offset_for_ref_frame[i]; + + if (abs_frame_num > 0) { + const int poc_cycle_cnt = ( abs_frame_num - 1 ) / dec->pic_order_cnt_cycle_length; + const int frame_num_in_poc_cycle = ( abs_frame_num - 1 ) % dec->pic_order_cnt_cycle_length; + + expected_poc = poc_cycle_cnt * expected_delta_per_poc_cycle; + for (int i = 0; i <= frame_num_in_poc_cycle; i++) + expected_poc += dec->offset_for_ref_frame[i]; + } else { + expected_poc = 0; + } + + if (dec->nal_ref_idc == 0) + expected_poc += dec->offset_for_non_ref_pic; + + field_poc[0] = expected_poc + dec->delta_pic_order_cnt[0]; + field_poc[1] = field_poc[0] + dec->offset_for_top_to_bottom_field; + + if (pic_type == H264_PICTURE_FRAME) + field_poc[1] += dec->delta_pic_order_cnt[1]; + + } else if (dec->pic_order_cnt_type == 2) { + int poc; + if (dec->nal_unit_type == H264_NAL_TYPE_IDR_SLICE) { + poc = 0; + } else { + const int abs_frame_num = dec->frame_num_offset + dec->frame_num; + if (dec->nal_ref_idc != 0) + poc = 2 * abs_frame_num; + else + poc = 2 * abs_frame_num - 1; + } + field_poc[0] = poc; + field_poc[1] = poc; + } + + /* */ + if (pic_type == H264_PICTURE_FRAME) + dec->pic_order_cnt = MIN(field_poc[0], field_poc[1] ); + else if (pic_type == H264_PICTURE_FIELD_TOP) + dec->pic_order_cnt = field_poc[0]; + else + dec->pic_order_cnt = field_poc[1]; +} + + +extern "C" int h264_detect_boundary (const uint8_t *buffer, + uint32_t buflen, + h264_decode_t *decode) +{ + uint8_t temp; + h264_decode_t new_decode; + int ret; + int slice = 0; + memcpy(&new_decode, decode, sizeof(new_decode)); + + temp = new_decode.nal_unit_type = h264_nal_unit_type(buffer); + new_decode.nal_ref_idc = h264_nal_ref_idc(buffer); + ret = 0; + switch (temp) { + case H264_NAL_TYPE_ACCESS_UNIT: + case H264_NAL_TYPE_END_OF_SEQ: + case H264_NAL_TYPE_END_OF_STREAM: +#ifdef BOUND_VERBOSE + printf("nal type %d\n", temp); +#endif + ret = 1; + break; + case H264_NAL_TYPE_NON_IDR_SLICE: + case H264_NAL_TYPE_DP_A_SLICE: + case H264_NAL_TYPE_DP_B_SLICE: + case H264_NAL_TYPE_DP_C_SLICE: + case H264_NAL_TYPE_IDR_SLICE: + slice = 1; + // slice buffer - read the info into the new_decode, and compare. + if (h264_read_slice_info(buffer, buflen, &new_decode) < 0) { + // need more memory + return -1; + } + if (decode->nal_unit_type > H264_NAL_TYPE_IDR_SLICE || + decode->nal_unit_type < H264_NAL_TYPE_NON_IDR_SLICE) { + break; + } + if (decode->frame_num != new_decode.frame_num) { +#ifdef BOUND_VERBOSE + printf("frame num values different %u %u\n", decode->frame_num, + new_decode.frame_num); +#endif + ret = 1; + break; + } + if (decode->field_pic_flag != new_decode.field_pic_flag) { + ret = 1; +#ifdef BOUND_VERBOSE + printf("field pic values different\n"); +#endif + break; + } + if (decode->nal_ref_idc != new_decode.nal_ref_idc && + (decode->nal_ref_idc == 0 || + new_decode.nal_ref_idc == 0)) { +#ifdef BOUND_VERBOSE + printf("nal ref idc values differ\n"); +#endif + ret = 1; + break; + } + if (decode->frame_num == new_decode.frame_num && + decode->pic_order_cnt_type == new_decode.pic_order_cnt_type) { + if (decode->pic_order_cnt_type == 0) { + if (decode->pic_order_cnt_lsb != new_decode.pic_order_cnt_lsb) { +#ifdef BOUND_VERBOSE + printf("pic order 1\n"); +#endif + ret = 1; + break; + } + if (decode->delta_pic_order_cnt_bottom != new_decode.delta_pic_order_cnt_bottom) { + ret = 1; +#ifdef BOUND_VERBOSE + printf("delta pic order cnt bottom 1\n"); +#endif + break; + } + } else if (decode->pic_order_cnt_type == 1) { + if (decode->delta_pic_order_cnt[0] != new_decode.delta_pic_order_cnt[0]) { + ret =1; +#ifdef BOUND_VERBOSE + printf("delta pic order cnt [0]\n"); +#endif + break; + } + if (decode->delta_pic_order_cnt[1] != new_decode.delta_pic_order_cnt[1]) { + ret = 1; +#ifdef BOUND_VERBOSE + printf("delta pic order cnt [1]\n"); +#endif + break; + + } + } + } + if (decode->nal_unit_type == H264_NAL_TYPE_IDR_SLICE && + new_decode.nal_unit_type == H264_NAL_TYPE_IDR_SLICE) { + if (decode->idr_pic_id != new_decode.idr_pic_id) { +#ifdef BOUND_VERBOSE + printf("idr_pic id\n"); +#endif + + ret = 1; + break; + } + } + break; + case H264_NAL_TYPE_SEQ_PARAM: + if (h264_read_seq_info(buffer, buflen, &new_decode) < 0) { + return -1; + } + // fall through + default: + if (decode->nal_unit_type <= H264_NAL_TYPE_IDR_SLICE) ret = 1; + else ret = 0; + } + + /* save _prev values */ + if (ret) + { + new_decode.frame_num_offset_prev = decode->frame_num_offset; + if (decode->pic_order_cnt_type != 2 || decode->nal_ref_idc != 0) + new_decode.frame_num_prev = decode->frame_num; + if (decode->nal_ref_idc != 0) + { + new_decode.pic_order_cnt_lsb_prev = decode->pic_order_cnt_lsb; + new_decode.pic_order_cnt_msb_prev = decode->pic_order_cnt_msb; + } + } + + if( slice ) { // XXX we compute poc for every slice in a picture (but it's not needed) + h264_compute_poc( &new_decode ); + } + + + // other types (6, 7, 8, +#ifdef BOUND_VERBOSE + if (ret == 0) { + printf("no change\n"); + } +#endif + + memcpy(decode, &new_decode, sizeof(*decode)); + return ret; +} + +uint32_t h264_read_sei_value (const uint8_t *buffer, uint32_t *size) +{ + uint32_t ret = 0; + *size = 1; + while (buffer[*size] == 0xff) { + ret += 255; + *size = *size + 1; + } + ret += *buffer; + return ret; +} + +extern "C" const char *h264_get_frame_type (h264_decode_t *dec) +{ + if (dec->nal_unit_type == H264_NAL_TYPE_IDR_SLICE) { + if (H264_TYPE_IS_I(dec->slice_type)) return "IDR"; + if (H264_TYPE_IS_SI(dec->slice_type)) return "IDR"; + } + else { + if (H264_TYPE_IS_P(dec->slice_type)) return "P"; + if (H264_TYPE_IS_B(dec->slice_type)) { + if (dec->nal_ref_idc) { + return "BREF"; + } + else { + return "B"; + } + } + if (H264_TYPE_IS_I(dec->slice_type)) return "I"; + if (H264_TYPE_IS_SI(dec->slice_type)) return "SI"; + if (H264_TYPE_IS_SP(dec->slice_type)) return "SP"; + } + return "UNK"; +} + +extern "C" uint32_t h264_get_frame_dependency (h264_decode_t *dec) +{ + uint32_t dflags = 0; + + if (dec->nal_ref_idc) + dflags |= MP4_SDT_HAS_DEPENDENTS; + else + dflags |= MP4_SDT_HAS_NO_DEPENDENTS; /* disposable */ + + if (dec->nal_unit_type != H264_NAL_TYPE_IDR_SLICE) { + if (H264_TYPE_IS_P(dec->slice_type)) dflags |= MP4_SDT_EARLIER_DISPLAY_TIMES_ALLOWED; + if (H264_TYPE_IS_I(dec->slice_type)) dflags |= MP4_SDT_EARLIER_DISPLAY_TIMES_ALLOWED;; + } + + return dflags; +} + +extern "C" const char *h264_get_slice_name (const uint8_t slice_type) +{ + if (H264_TYPE_IS_P(slice_type)) return "P"; + if (H264_TYPE_IS_B(slice_type)) return "B"; + if (H264_TYPE_IS_I(slice_type)) return "I"; + if (H264_TYPE_IS_SI(slice_type)) return "SI"; + if (H264_TYPE_IS_SP(slice_type)) return "SP"; + return "UNK"; +} + +extern "C" bool h264_access_unit_is_sync (const uint8_t *pNal, uint32_t len) +{ + uint8_t nal_type; + h264_decode_t dec; + uint32_t offset; + do { + nal_type = h264_nal_unit_type(pNal); + if (nal_type == H264_NAL_TYPE_SEQ_PARAM) return true; + if (nal_type == H264_NAL_TYPE_PIC_PARAM) return true; + if (nal_type == H264_NAL_TYPE_IDR_SLICE) return true; + if (h264_nal_unit_type_is_slice(nal_type)) { + if (h264_read_slice_info(pNal, len, &dec) < 0) return false; + if (H264_TYPE_IS_I(dec.slice_type) || + H264_TYPE_IS_SI(dec.slice_type)) return true; + return false; + } + offset = h264_find_next_start_code(pNal, len); + if (offset == 0 || offset > len) return false; + pNal += offset; + len -= offset; + } while (len > 0); + return false; +} + +extern "C" char *h264_get_profile_level_string (const uint8_t profile, + const uint8_t level) +{ + const char *pro; + char profileb[20], levelb[20]; + if (profile == 66) { + pro = "Baseline"; + } else if (profile == 77) { + pro = "Main"; + } else if (profile == 88) { + pro = "Extended"; + } else if (profile == 100) { + pro = "High"; + } else if (profile == 110) { + pro = "High 10"; + } else if (profile == 122) { + pro = "High 4:2:2"; + } else if (profile == 144) { + pro = "High 4:4:4"; + } else if (profile == 244) { + pro = "High 4:4:4 Predictive"; + } else { + snprintf(profileb, sizeof(profileb), "Unknown Profile %x", profile); + pro = profileb; + } + switch (level) { + case 10: case 20: case 30: case 40: case 50: + snprintf(levelb, sizeof(levelb), "%u", level / 10); + break; + case 11: case 12: case 13: + case 21: case 22: + case 31: case 32: + case 41: case 42: + case 51: + snprintf(levelb, sizeof(levelb), "%u.%u", level / 10, level % 10); + break; + default: + snprintf(levelb, sizeof(levelb), "unknown level %x", level); + break; + } + uint len = + 1 + strlen("H.264 @") + strlen(pro) + strlen(levelb); + char *typebuffer = + (char *)malloc(len); + if (typebuffer == NULL) return NULL; + + snprintf(typebuffer, len, "H.264 %s@%s", pro, levelb); + return typebuffer; +} + + +void DpbInit( h264_dpb_t *p ) +{ + p->dpb.cnt = 0; + p->dpb.next = 0; + p->dpb.size_min = 0; + + p->cnt = 0; + p->cnt_max = 0; + p->frame = NULL; +} +void DpbClean( h264_dpb_t *p ) +{ + free( p->frame ); +} +static void DpbUpdate( h264_dpb_t *p, int is_forced ) +{ + int i; + int pos; + + if (!is_forced && p->dpb.cnt < 16) + return; + + /* find the lowest poc */ + pos = 0; + for (i = 1; i < p->dpb.cnt; i++) + { + if (p->dpb.poc[i] < p->dpb.poc[pos]) + pos = i; + } + //fprintf( stderr, "lowest=%d\n", pos ); + + /* save the idx */ + if (p->dpb.idx[pos] >= p->cnt_max) + { + int inc = 1000 + (p->dpb.idx[pos]-p->cnt_max); + p->cnt_max += inc; + p->frame = (int*)realloc( p->frame, sizeof(int)*p->cnt_max ); + for (i=0;iframe[p->cnt_max-inc+i] = -1; /* To detect errors latter */ + } + p->frame[p->dpb.idx[pos]] = p->cnt++; + + /* Update the dpb minimal size */ + if (pos > p->dpb.size_min) + p->dpb.size_min = pos; + + /* update dpb */ + for (i = pos; i < p->dpb.cnt-1; i++) + { + p->dpb.idx[i] = p->dpb.idx[i+1]; + p->dpb.poc[i] = p->dpb.poc[i+1]; + } + p->dpb.cnt--; +} + +void DpbFlush( h264_dpb_t *p ) +{ + while (p->dpb.cnt > 0) + DpbUpdate( p, true ); +} + +void DpbAdd( h264_dpb_t *p, int poc, int is_idr ) +{ + if (is_idr) + DpbFlush( p ); + + p->dpb.idx[p->dpb.cnt] = p->dpb.next; + p->dpb.poc[p->dpb.cnt] = poc; + p->dpb.cnt++; + p->dpb.next++; + + DpbUpdate( p, false ); +} + +int DpbFrameOffset( h264_dpb_t *p, int idx ) +{ + if (idx >= p->cnt) + return 0; + if (p->frame[idx] < 0) + return p->dpb.size_min; /* We have an error (probably broken/truncated bitstream) */ + + return p->dpb.size_min + p->frame[idx] - idx; +} + + +static bool remove_unused_sei_messages (nal_reader_t *nal, + uint32_t header_size) +{ + uint32_t buffer_on = header_size; + buffer_on++; // increment past SEI message header + + while (buffer_on < nal->buffer_on) { + uint32_t payload_type, payload_size, start, size; + if (nal->buffer[buffer_on] == 0x80) { + // rbsp_trailing_bits + return true; + } + if (nal->buffer_on - buffer_on <= 2) { + //fprintf(stderr, "extra bytes after SEI message\n"); +#if 0 + memset(nal->buffer + buffer_on, 0, + nal->buffer_on - buffer_on); + nal->buffer_on = buffer_on; +#endif + + return true; + } + start = buffer_on; + payload_type = h264_read_sei_value(nal->buffer + buffer_on, + &size); +#ifdef DEBUG_H264 + printf("sei type %d size %d on %d\n", payload_type, + size, buffer_on); +#endif + buffer_on += size; + payload_size = h264_read_sei_value(nal->buffer + buffer_on, + &size); + buffer_on += size + payload_size; +#ifdef DEBUG_H264 + printf("sei size %d size %d on %d nal %d\n", + payload_size, size, buffer_on, nal->buffer_on); +#endif + if (buffer_on > nal->buffer_on) { + fprintf(stderr, "Error decoding sei message\n"); + return false; + } + switch (payload_type) { + case 3: + case 10: + case 11: + case 12: + memmove(nal->buffer + start, + nal->buffer + buffer_on, + nal->buffer_size - buffer_on); + nal->buffer_size -= buffer_on - start; + nal->buffer_on -= buffer_on - start; + buffer_on = start; + break; + } + } + if (nal->buffer_on == header_size) return false; + return true; +} + +static bool RefreshReader (nal_reader_t *nal, + uint32_t nal_start) +{ + uint32_t bytes_left; + uint32_t bytes_read; +#ifdef DEBUG_H264_READER + printf("refresh - start %u buffer on %u size %u\n", + nal_start, nal->buffer_on, nal->buffer_size); +#endif + if (nal_start != 0) { + if (nal_start > nal->buffer_size) { +#ifdef DEBUG_H264 + printf("nal start is greater than buffer size\n"); +#endif + nal->buffer_on = 0; + } else { + bytes_left = nal->buffer_size - nal_start; + if (bytes_left > 0) { + memmove(nal->buffer, + nal->buffer + nal_start, + bytes_left); + nal->buffer_on -= nal_start; +#ifdef DEBUG_H264_READER + printf("move %u new on is %u\n", bytes_left, nal->buffer_on); +#endif + } else { + nal->buffer_on = 0; + } + nal->buffer_size = bytes_left; + } + } else { + if (feof(nal->ifile)) { + return false; + } + nal->buffer_size_max += 4096 * 4; + nal->buffer = (uint8_t *)realloc(nal->buffer, nal->buffer_size_max); + } + bytes_read = fread(nal->buffer + nal->buffer_size, + 1, + nal->buffer_size_max - nal->buffer_size, + nal->ifile); + if (bytes_read == 0) return false; +#ifdef DEBUG_H264_READER + printf("read %u of %u\n", bytes_read, + nal->buffer_size_max - nal->buffer_size); +#endif + nal->buffer_size += bytes_read; + return true; +} + +static bool LoadNal (nal_reader_t *nal) +{ + if (nal->buffer_on != 0 || nal->buffer_size == 0) { + if (RefreshReader(nal, nal->buffer_on) == false) { +#ifdef DEBUG_H264 + printf("refresh returned 0 - buffer on is %u, size %u\n", + nal->buffer_on, nal->buffer_size); +#endif + if (nal->buffer_on >= nal->buffer_size) return false; + // continue + } + } + // find start code + uint32_t start; + if (h264_is_start_code(nal->buffer) == false) { + start = h264_find_next_start_code(nal->buffer, + nal->buffer_size); + RefreshReader(nal, start); + } + while ((start = h264_find_next_start_code(nal->buffer + 4, + nal->buffer_size - 4)) == 0) { + if (RefreshReader(nal, 0) == false) { + // end of file - use the last NAL + nal->buffer_on = nal->buffer_size; + return true; + } + } + nal->buffer_on = start + 4; + return true; +} + +NSData* H264Info(const char *filePath, uint32_t *pic_width, uint32_t *pic_height, uint8_t *profile, uint8_t *level) +{ + // track configuration info + NSMutableData *avcCData = [[NSMutableData alloc] init]; + uint8_t AVCProfileIndication = 0; + uint8_t profile_compat = 0; + uint8_t AVCLevelIndication = 0; + uint8_t configurationVersion = 0; + uint8_t sampleLenFieldSizeMinusOne = 3; + + bool have_seq = false; + bool have_pic = false; + uint8_t nal_type; + nal_reader_t nal; + h264_decode_t h264_dec; + FILE *inFile; + + inFile = fopen(filePath, "r"); + if (inFile == NULL) { + [avcCData release]; + return 0; + } + + memset(&nal, 0, sizeof(nal)); + nal.ifile = inFile; + + while (have_seq == false || have_pic == false) { + if (LoadNal(&nal) == false) { + // fprintf(stderr, "%s: Could not find sequence header\n", ProgName); + fclose(inFile); + [avcCData release]; + return nil; + } + uint32_t header_size = nal.buffer[2] == 1 ? 3 : 4; + + nal_type = h264_nal_unit_type(nal.buffer); + if (nal_type == H264_NAL_TYPE_SEQ_PARAM && !have_seq) { + have_seq = true; + uint32_t offset; + if (nal.buffer[2] == 1) offset = 3; + else offset = 4; + + AVCProfileIndication = nal.buffer[offset + 1]; + profile_compat = nal.buffer[offset + 2]; + AVCLevelIndication = nal.buffer[offset + 3]; + + [avcCData appendBytes:&configurationVersion length:sizeof(uint8_t)]; + [avcCData appendBytes:&AVCProfileIndication length:sizeof(uint8_t)]; + [avcCData appendBytes:&profile_compat length:sizeof(uint8_t)]; + [avcCData appendBytes:&AVCLevelIndication length:sizeof(uint8_t)]; + [avcCData appendBytes:&sampleLenFieldSizeMinusOne length:sizeof(uint8_t)]; + + uint8_t *buffer = nal.buffer + header_size; + uint32_t buffersize = nal.buffer_on - header_size; + uint32_t iy = 0; + + NSMutableData *seqData = [[NSMutableData alloc] init]; + uint16_t temp = buffersize << 8; + [seqData appendBytes:&temp length:sizeof(uint16_t)]; + [seqData appendBytes:buffer length:buffersize]; + iy++; + + [avcCData appendBytes:&iy length:sizeof(uint8_t)]; + [avcCData appendData:seqData]; + + [seqData release]; + + // skip the nal type byte + if (h264_read_seq_info(nal.buffer, nal.buffer_on, &h264_dec) == -1) + { + // fprintf(stderr, "%s: Could not decode Sequence header\n", ProgName); + fclose(inFile); + return nil; + } + *pic_width = h264_dec.pic_width; + *pic_height = h264_dec.pic_height; + *profile = h264_dec.profile; + *level = h264_dec.level; + } + else if (nal_type == H264_NAL_TYPE_PIC_PARAM && !have_pic) { + have_pic = true; + + uint8_t *buffer = nal.buffer + header_size; + uint32_t buffersize = nal.buffer_on - header_size; + + uint32_t iy = 0; + + NSMutableData *pictData = [[NSMutableData alloc] init]; + uint16_t temp = buffersize << 8; + [pictData appendBytes:&temp length:sizeof(uint16_t)]; + [pictData appendBytes:buffer length:buffersize]; + iy++; + + [avcCData appendBytes:&iy length:sizeof(uint8_t)]; + [avcCData appendData:pictData]; + + [pictData release]; + + } + } + + fclose(inFile); + return avcCData; +} + +@implementation MP42H264Importer + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError +{ + if ((self = [super init])) { + _fileURL = [fileURL retain]; + + _tracksArray = [[NSMutableArray alloc] initWithCapacity:1]; + + MP42VideoTrack *newTrack = [[MP42VideoTrack alloc] init]; + + newTrack.format = MP42VideoFormatH264; + newTrack.sourceURL = _fileURL; + + if (!inFile) + inFile = fopen([[_fileURL path] UTF8String], "rb"); + + struct stat st; + stat([[_fileURL path] UTF8String], &st); + _size = st.st_size; + + uint32_t tw, th; + uint8_t profile, level; + if ((avcC = H264Info([[_fileURL path] cStringUsingEncoding:NSASCIIStringEncoding], &tw, &th, &profile, &level))) { + newTrack.width = newTrack.trackWidth = tw; + newTrack.height = newTrack.trackHeight = th; + newTrack.hSpacing = newTrack.vSpacing = 1; + newTrack.origProfile = newTrack.newProfile = profile; + newTrack.origLevel = newTrack.newLevel = level; + } + + [newTrack setDataLength:[[[[NSFileManager defaultManager] attributesOfItemAtPath:[_fileURL path] error:nil] valueForKey:NSFileSize] unsignedLongLongValue]]; + + [_tracksArray addObject:newTrack]; + [newTrack release]; + } + + return self; +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + framerate_t * framerate; + + for (framerate = (framerate_t*) framerates; framerate->code; framerate++) + if([track sourceId] == framerate->code) + break; + + timescale = framerate->timescale; + mp4FrameDuration = framerate->duration; + + return timescale; +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + return NSMakeSize([(MP42VideoTrack*)track trackWidth], [(MP42VideoTrack*) track trackHeight]); +} + +- (NSData *)magicCookieForTrack:(MP42Track *)track +{ + return avcC; +} + +- (void)demux:(id)sender +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + if (!inFile) + inFile = fopen([[_fileURL path] UTF8String], "rb"); + + MP42Track *track = [_inputTracks lastObject]; + MP4TrackId trackId = [track sourceId]; + + framerate_t * framerate; + int64_t currentSize = 0; + + for (framerate = (framerate_t*) framerates; framerate->code; framerate++) + if([track sourceId] == framerate->code) + break; + + timescale = framerate->timescale; + mp4FrameDuration = framerate->duration; + + // the current syntactical object + // typically 1:1 with a sample + // but not always, i.e. non-VOP's + // the current sample + MP4SampleId sampleId = 1; + + // track configuration info + nal_reader_t nal; + h264_decode_t h264_dec; + + memset(&nal, 0, sizeof(nal)); + nal.ifile = inFile; + + if (timescale == 0) { + fprintf(stderr, "%s: Must specify a timescale when reading H.264 files", + ProgName); + timescale = 30000; + mp4FrameDuration = 1001; + } + + rewind(nal.ifile); + nal.buffer_size = 0; + nal.buffer_on = 0; + nal.buffer_size_max = 0; + free(nal.buffer); + nal.buffer = NULL; + + uint8_t *nal_buffer; + uint32_t nal_buffer_size, nal_buffer_size_max; + nal_buffer = NULL; + nal_buffer_size = 0; + nal_buffer_size_max = 0; + bool first = true; + bool nal_is_sync = false; + bool slice_is_idr = false; + int32_t poc = 0; + uint32_t dflags = 0; + + // now process the rest of the video stream + memset(&h264_dec, 0, sizeof(h264_dec)); + DpbInit(&h264_dpb); + + while ( (LoadNal(&nal) != false) && !_cancelled) { + uint32_t header_size; + header_size = nal.buffer[2] == 1 ? 3 : 4; + bool boundary = h264_detect_boundary(nal.buffer, + nal.buffer_on, + &h264_dec); + + if (boundary && first == false) { + // write the previous sample + if (nal_buffer_size != 0) { + samplesWritten++; + + void* sampleData = malloc(nal_buffer_size); + memcpy(sampleData, nal_buffer, nal_buffer_size); + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = sampleData; + sample->size = nal_buffer_size; + sample->duration = mp4FrameDuration; + sample->offset = 0; + sample->timestamp = 0; + sample->isSync = nal_is_sync; + sample->trackId = trackId; + + [self enqueue:sample]; + [sample release]; + + currentSize += nal_buffer_size; + _progress = (currentSize / (CGFloat) _size) * 100; + + sampleId++; + DpbAdd( &h264_dpb, poc, slice_is_idr ); + nal_is_sync = false; + nal_buffer_size = 0; + } + } + bool copy_nal_to_buffer = false; + if (Verbosity) { + printf("H264 type %x size %u\n", + h264_dec.nal_unit_type, nal.buffer_on); + } + if (h264_nal_unit_type_is_slice(h264_dec.nal_unit_type)) { + dflags = h264_get_frame_dependency(&h264_dec); + // copy all seis, etc before indicating first + first = false; + copy_nal_to_buffer = true; + slice_is_idr = h264_dec.nal_unit_type == H264_NAL_TYPE_IDR_SLICE; + poc = h264_dec.pic_order_cnt; + + nal_is_sync = h264_slice_is_idr(&h264_dec); + } else { + + switch (h264_dec.nal_unit_type) { + case H264_NAL_TYPE_SEQ_PARAM: + // doesn't get added to sample buffer + // remove header + //MP4AddH264SequenceParameterSet(mp4File, trackId, + // nal.buffer + header_size, + // nal.buffer_on - header_size); + //break; + case H264_NAL_TYPE_PIC_PARAM: + // doesn't get added to sample buffer + //MP4AddH264PictureParameterSet(mp4File, trackId, + // nal.buffer + header_size, + // nal.buffer_on - header_size); + //break; + case H264_NAL_TYPE_FILLER_DATA: + // doesn't get copied + //break; + case H264_NAL_TYPE_SEI: + //copy_nal_to_buffer = remove_unused_sei_messages(&nal, header_size); + //break; + case H264_NAL_TYPE_ACCESS_UNIT: + // note - may not want to copy this - not needed + default: + copy_nal_to_buffer = true; + break; + } + } + if (copy_nal_to_buffer) { + uint32_t to_write; + to_write = nal.buffer_on - header_size; + if (to_write + 4 + nal_buffer_size > nal_buffer_size_max) { + nal_buffer_size_max += nal.buffer_on + 4; + nal_buffer = (uint8_t *)realloc(nal_buffer, nal_buffer_size_max); + } + nal_buffer[nal_buffer_size] = (to_write >> 24) & 0xff; + nal_buffer[nal_buffer_size + 1] = (to_write >> 16) & 0xff; + nal_buffer[nal_buffer_size + 2] = (to_write >> 8) & 0xff; + nal_buffer[nal_buffer_size + 3] = to_write & 0xff; + memcpy(nal_buffer + nal_buffer_size + 4, + nal.buffer + header_size, + to_write); + + nal_buffer_size += to_write + 4; + } + } + + if (nal_buffer_size != 0) { + samplesWritten++; + + void *sampleData = malloc(nal_buffer_size); + memcpy(sampleData, nal_buffer, nal_buffer_size); + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = sampleData; + sample->size = nal_buffer_size; + sample->duration = mp4FrameDuration; + sample->offset = 0; + sample->timestamp = 0; + sample->isSync = nal_is_sync; + sample->trackId = trackId; + + [self enqueue:sample]; + [sample release]; + + currentSize += nal_buffer_size; + _progress = (currentSize / (CGFloat) _size) * 100; + + DpbAdd(&h264_dpb, h264_dec.pic_order_cnt, slice_is_idr); + } + + DpbFlush(&h264_dpb); + free(nal_buffer); + + [self setDone:YES]; + [pool release]; +} + +- (BOOL)cleanUp:(MP4FileHandle)fileHandle +{ + MP42Track *track = [_inputTracks lastObject]; + MP4TrackId trackId = [track Id]; + + if (h264_dpb.dpb.size_min > 0) { + unsigned int ix; + + for (ix = 0; ix < samplesWritten; ix++) { + const int offset = DpbFrameOffset(&h264_dpb, ix); + MP4SetSampleRenderingOffset(fileHandle, trackId, 1 + ix, + offset * mp4FrameDuration); + } + MP4Duration editDuration = MP4ConvertFromTrackDuration(fileHandle, + trackId, + MP4GetTrackDuration(fileHandle, trackId), + MP4GetTimeScale(fileHandle)); + + MP4AddTrackEdit(fileHandle, trackId, MP4_INVALID_EDIT_ID, DpbFrameOffset(&h264_dpb, 0) * mp4FrameDuration, + editDuration, 0); + } + + DpbClean(&h264_dpb); + + return YES; +} + +- (void)startReading +{ + [super startReading]; + + if (!_demuxerThread && !_done) { + _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; + [_demuxerThread setName:@"H264 Demuxer"]; + [_demuxerThread start]; + } +} + +- (void) dealloc +{ + [avcC release]; + fclose(inFile); + + [super dealloc]; +} + +@end diff --git a/MP42/MP42HtmlParser.h b/MP42/MP42HtmlParser.h new file mode 100644 index 0000000..27d9594 --- /dev/null +++ b/MP42/MP42HtmlParser.h @@ -0,0 +1,64 @@ +// +// SBHtmlParser.h +// Subler +// +// Created by Damiano Galassi on 13/06/13. +// +// + +#import + +#define kStyleBold 1 +#define kStyleItalic 2 +#define kStyleUnderlined 4 +#define kStyleColor 8 + +#define kTagOpen 1 +#define kTagClose 2 + +typedef struct rgba_color { + u_int8_t r; + u_int8_t g; + u_int8_t b; + u_int8_t a; +} rgba_color; + +rgba_color make_color(u_int8_t r, u_int8_t g, u_int8_t b, u_int8_t a); +int compare_color(rgba_color c1, rgba_color c2); + +@interface MP42Style : NSObject +{ + NSInteger _style; + rgba_color _color; + NSInteger _type; + NSUInteger _location; + NSUInteger _length; +} + +- (instancetype)initWithStyle:(NSInteger)style type:(NSInteger)type location:(NSUInteger) location color:(rgba_color) color; + +@property (readwrite) NSInteger style; +@property (readwrite) rgba_color color; +@property (readwrite) NSInteger type; +@property (readwrite) NSUInteger location; +@property (readwrite) NSUInteger length; + +@end + +@interface MP42HtmlParser : NSObject +{ + NSUInteger _location; + NSMutableString *_text; + NSMutableArray *_styles; + rgba_color _defaultColor; +} + +@property (readonly) NSString *text; +@property (readonly) NSArray *styles; +@property (readwrite) rgba_color defaultColor; + +- (instancetype)initWithString:(NSString *)string; +- (NSInteger) parseNextTag; +- (void)serializeStyles; + +@end diff --git a/MP42/MP42HtmlParser.m b/MP42/MP42HtmlParser.m new file mode 100644 index 0000000..365832d --- /dev/null +++ b/MP42/MP42HtmlParser.m @@ -0,0 +1,226 @@ +// +// SBHtmlParser.m +// Subler +// +// Created by Damiano Galassi on 13/06/13. +// +// + +#import "MP42HtmlParser.h" + +rgba_color make_color(u_int8_t r, u_int8_t g, u_int8_t b, u_int8_t a) { + rgba_color color; + color.r = r; + color.g = g; + color.b = b; + color.a = a; + return color; +} + +int compare_color(rgba_color c1, rgba_color c2) { + if (c1.r == c2.r && + c1.g == c2.g && + c1.b == c2.b && + c1.a == c2.a) + return 0; + else + return 1; +} +@implementation MP42Style + +- (instancetype)init { + self = [super init]; + if (self) { + _color = make_color(255, 255, 255, 255); + } + return self; +} + +- (instancetype)initWithStyle:(NSInteger)style type:(NSInteger)type location:(NSUInteger) location color:(rgba_color) color +{ + self = [super init]; + if (self) { + _style = style; + _type = type; + _location = location; + _color = color; + + } + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone +{ + MP42Style *newObject = [[MP42Style allocWithZone:zone] init]; + + newObject.style = _style; + newObject.type = _type; + newObject.location = _location; + newObject.length = _length; + newObject.color = _color; + + return newObject; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"Style: %ld\n, Location: %lu, Length: %lu", (long)_style, (unsigned long)_location, (unsigned long)_length]; +} + +@synthesize style = _style; +@synthesize color = _color; +@synthesize type = _type; +@synthesize location = _location; +@synthesize length = _length; + +@end + +@implementation MP42HtmlParser + +- (instancetype)initWithString: (NSString*) string +{ + self = [super init]; + if (self) { + _text = [string mutableCopy]; + _styles = [[NSMutableArray alloc] init]; + } + return self; +} + +- (NSInteger)parseNextTag +{ + NSCharacterSet *openChar = [NSCharacterSet characterSetWithCharactersInString:@"<"]; + NSCharacterSet *closeChar = [NSCharacterSet characterSetWithCharactersInString:@">"]; + NSRange openRange; + NSRange closeRange; + + NSString *content; + + openRange = [_text rangeOfCharacterFromSet:openChar]; + if (openRange.location != NSNotFound) { + closeRange = [_text rangeOfCharacterFromSet:closeChar]; + + while (closeRange.location < openRange.location) { + [_text deleteCharactersInRange:closeRange]; + openRange.location--; + closeRange = [_text rangeOfCharacterFromSet:closeChar]; + } + + if (closeRange.location == NSNotFound) + closeRange.location = [_text length]; + } + else { + _location = [_text length]; + return NSNotFound; + } + + NSRange contentRange, contentInternalRange; + contentRange.location = openRange.location; + contentRange.length = closeRange.location + closeRange.length - openRange.location; + + contentInternalRange = contentRange; + contentInternalRange.location += 1; + contentInternalRange.length -= 2; + + content = [_text substringWithRange:contentInternalRange]; + + NSInteger tagType; + MP42Style *style = nil; + if ([content hasPrefix:@"/"]) { + tagType = kTagClose; + contentInternalRange.location +=1; + contentInternalRange.length -=1; + content = [_text substringWithRange:contentInternalRange]; + } + else + tagType = kTagOpen; + + if ([content hasPrefix:@"font"]) { + style = [[MP42Style alloc] initWithStyle:kStyleColor type:tagType location:openRange.location color: _defaultColor]; + if (tagType == kTagOpen) { + NSRange colorRange = [content rangeOfString:@"color=\"#"]; + if (colorRange.location != NSNotFound && colorRange.location < [content length]) { + colorRange.location += 8; + colorRange.length = 6; + NSString *color = [content substringWithRange:colorRange]; + const char *r = [[color substringWithRange:NSMakeRange(0, 2)] UTF8String]; + const char *g = [[color substringWithRange:NSMakeRange(2, 2)] UTF8String]; + const char *b = [[color substringWithRange:NSMakeRange(4, 2)] UTF8String]; + int rc, gc, bc; + sscanf(r, "%x", &rc); + sscanf(g, "%x", &gc); + sscanf(b, "%x", &bc); + style.color = make_color(rc,gc,bc,255); + } + } + } + else if ([content hasPrefix:@"b"]) { + style = [[MP42Style alloc] initWithStyle:kStyleBold type:tagType location:openRange.location color:_defaultColor]; + } + else if ([content hasPrefix:@"i"]) { + style = [[MP42Style alloc] initWithStyle:kStyleItalic type:tagType location:openRange.location color:_defaultColor]; + } + else if ([content hasPrefix:@"u"]) { + style = [[MP42Style alloc] initWithStyle:kStyleUnderlined type:tagType location:openRange.location color:_defaultColor]; + } + + if (style) { + [_styles addObject:style]; + [style release]; + } + + [_text deleteCharactersInRange:contentRange]; + + return contentRange.location; +} + +- (void)serializeStyles +{ + NSMutableArray *serializedStyles = [[NSMutableArray alloc] init]; + MP42Style *currentStyle = [[MP42Style alloc] init]; + + for (MP42Style *nextStyle in _styles) { + if (currentStyle.location != nextStyle.location) { + currentStyle.length = nextStyle.location - currentStyle.location; + if (currentStyle.style || compare_color(currentStyle.color, nextStyle.color)) + if (currentStyle.length) + [serializedStyles addObject:[[currentStyle copy] autorelease]]; + + currentStyle.location = nextStyle.location; + } + if (nextStyle.type == kTagOpen) { + if (nextStyle.style == kStyleColor) + currentStyle.color = nextStyle.color; + else + currentStyle.style |= nextStyle.style; + } + else if (nextStyle.type == kTagClose) { + if (nextStyle.style == kStyleColor) + currentStyle.color = _defaultColor; + else + currentStyle.style ^= nextStyle.style; + } + } + + if (currentStyle.style || compare_color(currentStyle.color, _defaultColor)) { + currentStyle.length = [_text length] - currentStyle.location; + if (currentStyle.length) + [serializedStyles addObject:[[currentStyle copy] autorelease]]; + } + + [currentStyle release]; + [_styles release]; + _styles = serializedStyles; +} + +@synthesize text = _text; +@synthesize styles = _styles; +@synthesize defaultColor = _defaultColor; + + +- (void)dealloc +{ + [_text release]; + [_styles release]; + [super dealloc]; +} +@end diff --git a/MP42/MP42Image.h b/MP42/MP42Image.h new file mode 100644 index 0000000..9928589 --- /dev/null +++ b/MP42/MP42Image.h @@ -0,0 +1,40 @@ +// +// MP42Image.h +// Subler +// +// Created by Damiano Galassi on 27/06/13. +// +// + +#import + +@class NSImage; + +typedef enum MP42TagArtworkType_e { + MP42_ART_UNDEFINED = 0, + MP42_ART_BMP = 1, + MP42_ART_GIF = 2, + MP42_ART_JPEG = 3, + MP42_ART_PNG = 4 +} MP42TagArtworkType; + +@interface MP42Image : NSObject { + NSImage *_image; + + NSURL *_url; + NSData *_data; + + NSInteger _type; +} + +- (instancetype)initWithURL:(NSURL *)url type:(NSInteger)type; +- (instancetype)initWithImage:(NSImage *)image; +- (instancetype)initWithData:(NSData *)data type:(NSInteger)type; +- (instancetype)initWithBytes:(const void*)bytes length:(NSUInteger)length type:(NSInteger)type; + +@property(readonly) NSImage *image; +@property(readonly) NSURL *url; +@property(readonly) NSData *data; +@property(readonly) NSInteger type; + +@end \ No newline at end of file diff --git a/MP42/MP42Image.m b/MP42/MP42Image.m new file mode 100644 index 0000000..f5e6644 --- /dev/null +++ b/MP42/MP42Image.m @@ -0,0 +1,135 @@ +// +// MP42Image.m +// Subler +// +// Created by Damiano Galassi on 27/06/13. +// +// + +#import "MP42Image.h" +#import + +@implementation MP42Image + +- (instancetype)initWithURL:(NSURL *)url type:(NSInteger)type +{ + if (self = [super init]) { + _url = [url retain]; + _type = type; + } + + return self; +} + +- (instancetype)initWithImage:(NSImage *)image +{ + if (self = [super init]) + _image = [image retain]; + + return self; +} + +- (instancetype)initWithData:(NSData *)data type:(NSInteger)type +{ + if (self = [super init]) { + _data = [data retain]; + _type = type; + } + + return self; +} + +- (instancetype)initWithBytes:(const void*)bytes length:(NSUInteger)length type:(NSInteger)type +{ + if (self = [super init]) { + _data = [[NSData alloc] initWithBytes:bytes length:length]; + _type = type; + } + + return self; +} + +- (NSImage *)imageFromData:(NSData *)data +{ + NSImage *image = nil; + NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data]; + if (imageRep != nil) { + image = [[NSImage alloc] initWithSize:[imageRep size]]; + [image addRepresentation:imageRep]; + } + + return [image autorelease]; +} + +- (NSData *)data { + if (_data) + return _data; + else if (_url) { + NSError *outError = nil; + _data = [[NSData dataWithContentsOfURL:_url options:NSDataReadingUncached error:&outError] retain]; + } + + return _data; +} + +- (NSImage *)image +{ + if (_image) + return _image; + else if (self.data) { + _image = [[self imageFromData:_data] retain]; + } + + return _image; +} + +- (NSString *)imageRepresentationType +{ + return IKImageBrowserNSImageRepresentationType; +} + +- (NSString *)imageUID +{ + return [self.image description]; +} + +- (id)imageRepresentation +{ + return self.image; +} + +- (void)encodeWithCoder:(NSCoder *)coder +{ + if (_data) + [coder encodeObject:_data forKey:@"MP42Image_Data"]; + else + [coder encodeObject:_image forKey:@"MP42Image"]; + + [coder encodeInteger:_type forKey:@"MP42ImageType"]; +} + +- (id)initWithCoder:(NSCoder *)decoder +{ + self = [super init]; + + _image = [[decoder decodeObjectForKey:@"MP42Image"] retain]; + _data = [[decoder decodeObjectForKey:@"MP42Image_Data"] retain]; + + _type = [decoder decodeIntForKey:@"MP42ImageType"]; + + return self; +} + +- (void)dealloc +{ + [_image release]; + [_data release]; + + [super dealloc]; +} + +@synthesize url = _url; +@synthesize data = _data; +@synthesize type = _type; + +@end \ No newline at end of file diff --git a/MP42/MP42MediaFormat.h b/MP42/MP42MediaFormat.h new file mode 100644 index 0000000..3ce08cf --- /dev/null +++ b/MP42/MP42MediaFormat.h @@ -0,0 +1,78 @@ +// +// MP42MediaFormat.h +// Subler +// +// Created by Damiano Galassi on 08/08/13. +// +// + +#import + +/* MP4 API types */ +typedef void* MP42FileHandle; +typedef uint32_t MP42TrackId; +typedef uint64_t MP42Duration; + +// File Type +extern NSString *const MP42FileTypeMP4; +extern NSString *const MP42FileTypeM4V; +extern NSString *const MP42FileTypeM4A; +extern NSString *const MP42FileTypeM4B; + + +// Media Type +extern NSString *const MP42MediaTypeVideo; +extern NSString *const MP42MediaTypeAudio; +extern NSString *const MP42MediaTypeText; +extern NSString *const MP42MediaTypeClosedCaption; +extern NSString *const MP42MediaTypeSubtitle; +extern NSString *const MP42MediaTypeTimecode; +extern NSString *const MP42MediaTypeMetadata; +extern NSString *const MP42MediaTypeMuxed; + + +// Video Format +extern NSString *const MP42VideoFormatH264; +extern NSString *const MP42VideoFormatMPEG4Visual; +extern NSString *const MP42VideoFormatSorenson; +extern NSString *const MP42VideoFormatSorenson3; +extern NSString *const MP42VideoFormatMPEG1; +extern NSString *const MP42VideoFormatMPEG2; +extern NSString *const MP42VideoFormatDV; +extern NSString *const MP42VideoFormatPNG; +extern NSString *const MP42VideoFormatAnimation; +extern NSString *const MP42VideoFormatProRes; +extern NSString *const MP42VideoFormatJPEG; +extern NSString *const MP42VideoFormatMotionJPEG; +extern NSString *const MP42VideoFormatFairPlay; + + +// Audio Format +extern NSString *const MP42AudioFormatAAC; +extern NSString *const MP42AudioFormatHEAAC; +extern NSString *const MP42AudioFormatMP3; +extern NSString *const MP42AudioFormatVorbis; +extern NSString *const MP42AudioFormatFLAC; +extern NSString *const MP42AudioFormatALAC; +extern NSString *const MP42AudioFormatAC3; +extern NSString *const MP42AudioFormatDTS; +extern NSString *const MP42AudioFormatTrueHD; +extern NSString *const MP42AudioFormatAMR; +extern NSString *const MP42AudioFormatPCM; +extern NSString *const MP42AudioFormatFairPlay; + + +// Subtitle Format +extern NSString *const MP42SubtitleFormatTx3g; +extern NSString *const MP42SubtitleFormatText; +extern NSString *const MP42SubtitleFormatVobSub; +extern NSString *const MP42SubtitleFormatPGS; +extern NSString *const MP42SubtitleFormatSSA; + +// Closed Caption Fromat +extern NSString *const MP42ClosedCaptionFormatCEA608; +extern NSString *const MP42ClosedCaptionFormatCEA708; + + +// TimeCode Format +extern NSString *const MP42TimeCodeFormat; \ No newline at end of file diff --git a/MP42/MP42MediaFormat.m b/MP42/MP42MediaFormat.m new file mode 100644 index 0000000..81af0be --- /dev/null +++ b/MP42/MP42MediaFormat.m @@ -0,0 +1,72 @@ +// +// MP42MediaFormat.h +// Subler +// +// Created by Damiano Galassi on 08/08/13. +// +// + +#import + +// File Type +NSString *const MP42FileTypeMP4 = @"mp4"; +NSString *const MP42FileTypeM4V = @"m4v"; +NSString *const MP42FileTypeM4A = @"m4a"; +NSString *const MP42FileTypeM4B = @"m4b"; + + +// Media Type +NSString *const MP42MediaTypeVideo = @"Video Track"; +NSString *const MP42MediaTypeAudio = @"Sound Track"; +NSString *const MP42MediaTypeText = @"Text Track"; +NSString *const MP42MediaTypeClosedCaption = @"Closed Caption Track"; +NSString *const MP42MediaTypeSubtitle = @"Subtitle Track"; +NSString *const MP42MediaTypeTimecode = @"TimeCode Track"; + + +// Video Format +NSString *const MP42VideoFormatH264 = @"H.264"; +NSString *const MP42VideoFormatMPEG4Visual = @"MPEG-4 Visual"; +NSString *const MP42VideoFormatSorenson = @"Sorenson Video"; +NSString *const MP42VideoFormatSorenson3 = @"Sorenson Video 3"; +NSString *const MP42VideoFormatMPEG1 = @"MPEG-1"; +NSString *const MP42VideoFormatMPEG2 = @"MPEG-2"; +NSString *const MP42VideoFormatDV = @"DV"; +NSString *const MP42VideoFormatPNG = @"PNG"; +NSString *const MP42VideoFormatAnimation = @"Animation"; +NSString *const MP42VideoFormatProRes = @"Apple ProRes"; +NSString *const MP42VideoFormatJPEG = @"Photo-JPEG"; +NSString *const MP42VideoFormatMotionJPEG = @"Motion JPEG"; +NSString *const MP42VideoFormatFairPlay = @"FairPlay Video"; + + +// Audio Format +NSString *const MP42AudioFormatAAC = @"AAC"; +NSString *const MP42AudioFormatHEAAC = @"HE-AAC"; +NSString *const MP42AudioFormatMP3 = @"MP3"; +NSString *const MP42AudioFormatVorbis = @"Vorbis"; +NSString *const MP42AudioFormatFLAC = @"FLAC"; +NSString *const MP42AudioFormatALAC = @"ALAC"; +NSString *const MP42AudioFormatAC3 = @"AC-3"; +NSString *const MP42AudioFormatDTS = @"DTS"; +NSString *const MP42AudioFormatTrueHD = @"True HD"; +NSString *const MP42AudioFormatAMR = @"AMR Narrow Band"; +NSString *const MP42AudioFormatPCM = @"PCM"; +NSString *const MP42AudioFormatFairPlay = @"FairPlay Sound"; + + +// Subtitle Format +NSString *const MP42SubtitleFormatTx3g = @"Tx3g"; +NSString *const MP42SubtitleFormatText = @"Text"; +NSString *const MP42SubtitleFormatVobSub = @"VobSub"; +NSString *const MP42SubtitleFormatPGS = @"PGS"; +NSString *const MP42SubtitleFormatSSA = @"SSA"; + + +// Closed Caption Fromat +NSString *const MP42ClosedCaptionFormatCEA608 = @"CEA-608"; +NSString *const MP42ClosedCaptionFormatCEA708 = @"CEA-708"; + + +// TimeCode Format +NSString *const MP42TimeCodeFormat = @"TimeCode"; \ No newline at end of file diff --git a/MP42/MP42Metadata.h b/MP42/MP42Metadata.h new file mode 100644 index 0000000..61a4a9b --- /dev/null +++ b/MP42/MP42Metadata.h @@ -0,0 +1,70 @@ +// +// MP42Metadata.h +// Subler +// +// Created by Damiano Galassi on 06/02/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import +#import "MP42MediaFormat.h" + +@interface MP42Metadata : NSObject { + NSString *presetName; + NSURL *sourceURL; + NSMutableDictionary *tagsDict; + + NSMutableArray *artworks; + + NSArray *artworkThumbURLs; + NSArray *artworkFullsizeURLs; + NSArray *artworkProviderNames; + + NSString *ratingiTunesCode; + + uint8_t mediaKind; + uint8_t contentRating; + uint8_t hdVideo; + uint8_t gapless; + uint8_t podcast; + BOOL isEdited; + BOOL isArtworkEdited; +} + +- (instancetype) initWithSourceURL:(NSURL *)URL fileHandle:(MP42FileHandle)fileHandle; +- (instancetype) initWithFileURL:(NSURL *)URL; + +- (NSArray *) availableMetadata; +- (NSArray *) writableMetadata; + +- (NSArray *) availableGenres; + +- (void) removeTagForKey:(NSString *)aKey; +- (BOOL) setTag:(id)value forKey:(NSString *)key; +- (BOOL) setMediaKindFromString:(NSString *)mediaKindString; +- (BOOL) setContentRatingFromString:(NSString *)contentRatingString; +- (BOOL) setArtworkFromFilePath:(NSString *)imageFilePath; + +- (BOOL) writeMetadataWithFileHandle: (MP42FileHandle *) fileHandle; + +- (BOOL) mergeMetadata: (MP42Metadata *) newMetadata; + +@property(readonly) NSMutableDictionary *tagsDict; + +@property(readwrite, retain) NSString *presetName; + +@property(readwrite, retain) NSMutableArray *artworks; + +@property(readwrite, retain) NSArray *artworkThumbURLs; +@property(readwrite, retain) NSArray *artworkFullsizeURLs; +@property(readwrite, retain) NSArray *artworkProviderNames; + +@property(readwrite) uint8_t mediaKind; +@property(readwrite) uint8_t contentRating; +@property(readwrite) uint8_t hdVideo; +@property(readwrite) uint8_t gapless; +@property(readwrite) uint8_t podcast; +@property(readwrite) BOOL isEdited; +@property(readwrite) BOOL isArtworkEdited; + +@end diff --git a/MP42/MP42Metadata.m b/MP42/MP42Metadata.m new file mode 100644 index 0000000..af431e9 --- /dev/null +++ b/MP42/MP42Metadata.m @@ -0,0 +1,1547 @@ +// +// MP42Metadata.m +// Subler +// +// Created by Damiano Galassi on 06/02/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import "MP42Metadata.h" +#import "MP42Utilities.h" +#import "MP42XMLReader.h" +#import "MP42Image.h" +#import "RegexKitLite.h" +#import "SBRatings.h" + +typedef struct mediaKind_t +{ + uint8_t stik; + NSString *english_name; +} mediaKind_t; + +static const mediaKind_t mediaKind_strings[] = { + {0, @"Home Video"}, + {1, @"Music"}, + {2, @"Audiobook"}, + {6, @"Music Video"}, + {9, @"Movie"}, + {10, @"TV Show"}, + {11, @"Booklet"}, + {14, @"Ringtone"}, + {21, @"Podcast"}, + {23, @"iTunes U"}, + {0, NULL}, +}; + +typedef struct contentRating_t +{ + uint8_t rtng; + NSString *english_name; +} contentRating_t; + +static const contentRating_t contentRating_strings[] = { + {0, @"None"}, + {2, @"Clean"}, + {4, @"Explicit"}, + {0, NULL}, +}; + +typedef struct genreType_t +{ + uint8_t index; + const char *short_name; + const char *english_name; +} genreType_t; + +static const genreType_t genreType_strings[] = { + {1, "blues", "Blues" }, + {2, "classicrock", "Classic Rock" }, + {3, "country", "Country" }, + {4, "dance", "Dance" }, + {5, "disco", "Disco" }, + {6, "funk", "Funk" }, + {7, "grunge", "Grunge" }, + {8, "hiphop", "Hop-Hop" }, + {9, "jazz", "Jazz" }, + {10, "metal", "Metal" }, + {11, "newage", "New Age" }, + {12, "oldies", "Oldies" }, + {13, "other", "Other" }, + {14, "pop", "Pop" }, + {15, "rand_b", "R&B" }, + {16, "rap", "Rap" }, + {17, "reggae", "Reggae" }, + {18, "rock", "Rock" }, + {19, "techno", "Techno" }, + {20, "industrial", "Industrial" }, + {21, "alternative", "Alternative" }, + {22, "ska", "Ska" }, + {23, "deathmetal", "Death Metal" }, + {24, "pranks", "Pranks" }, + {25, "soundtrack", "Soundtrack" }, + {26, "eurotechno", "Euro-Techno" }, + {27, "ambient", "Ambient" }, + {28, "triphop", "Trip-Hop" }, + {29, "vocal", "Vocal" }, + {30, "jazzfunk", "Jazz+Funk" }, + {31, "fusion", "Fusion" }, + {32, "trance", "Trance" }, + {33, "classical", "Classical" }, + {34, "instrumental", "Instrumental" }, + {35, "acid", "Acid" }, + {36, "house", "House" }, + {37, "game", "Game" }, + {38, "soundclip", "Sound Clip" }, + {39, "gospel", "Gospel" }, + {40, "noise", "Noise" }, + {41, "alternrock", "AlternRock" }, + {42, "bass", "Bass" }, + {43, "soul", "Soul" }, + {44, "punk", "Punk" }, + {45, "space", "Space" }, + {46, "meditative", "Meditative" }, + {47, "instrumentalpop", "Instrumental Pop" }, + {48, "instrumentalrock", "Instrumental Rock" }, + {49, "ethnic", "Ethnic" }, + {50, "gothic", "Gothic" }, + {51, "darkwave", "Darkwave" }, + {52, "technoindustrial", "Techno-Industrial" }, + {53, "electronic", "Electronic" }, + {54, "popfolk", "Pop-Folk" }, + {55, "eurodance", "Eurodance" }, + {56, "dream", "Dream" }, + {57, "southernrock", "Southern Rock" }, + {58, "comedy", "Comedy" }, + {59, "cult", "Cult" }, + {60, "gangsta", "Gangsta" }, + {61, "top40", "Top 40" }, + {62, "christianrap", "Christian Rap" }, + {63, "popfunk", "Pop/Funk" }, + {64, "jungle", "Jungle" }, + {65, "nativeamerican", "Native American" }, + {66, "cabaret", "Cabaret" }, + {67, "newwave", "New Wave" }, + {68, "psychedelic", "Psychedelic" }, + {69, "rave", "Rave" }, + {70, "showtunes", "Showtunes" }, + {71, "trailer", "Trailer" }, + {72, "lofi", "Lo-Fi" }, + {73, "tribal", "Tribal" }, + {74, "acidpunk", "Acid Punk" }, + {75, "acidjazz", "Acid Jazz" }, + {76, "polka", "Polka" }, + {77, "retro", "Retro" }, + {78, "musical", "Musical" }, + {79, "rockand_roll", "Rock & Roll" }, + + {80, "hardrock", "Hard Rock" }, + {81, "folk", "Folk" }, + {82, "folkrock", "Folk-Rock" }, + {83, "nationalfolk", "National Folk" }, + {84, "swing", "Swing" }, + {85, "fastfusion", "Fast Fusion" }, + {86, "bebob", "Bebob" }, + {87, "latin", "Latin" }, + {88, "revival", "Revival" }, + {89, "celtic", "Celtic" }, + {90, "bluegrass", "Bluegrass" }, + {91, "avantgarde", "Avantgarde" }, + {92, "gothicrock", "Gothic Rock" }, + {93, "progressiverock", "Progresive Rock" }, + {94, "psychedelicrock", "Psychedelic Rock" }, + {95, "symphonicrock", "SYMPHONIC_ROCK" }, + {96, "slowrock", "Slow Rock" }, + {97, "bigband", "Big Band" }, + {98, "chorus", "Chorus" }, + {99, "easylistening", "Easy Listening" }, + {100, "acoustic", "Acoustic" }, + {101, "humour", "Humor" }, + {102, "speech", "Speech" }, + {103, "chanson", "Chason" }, + {104, "opera", "Opera" }, + {105, "chambermusic", "Chamber Music" }, + {106, "sonata", "Sonata" }, + {107, "symphony", "Symphony" }, + {108, "bootybass", "Booty Bass" }, + {109, "primus", "Primus" }, + {110, "porngroove", "Porn Groove" }, + {111, "satire", "Satire" }, + {112, "slowjam", "Slow Jam" }, + {113, "club", "Club" }, + {114, "tango", "Tango" }, + {115, "samba", "Samba" }, + {116, "folklore", "Folklore" }, + {117, "ballad", "Ballad" }, + {118, "powerballad", "Power Ballad" }, + {119, "rhythmicsoul", "Rhythmic Soul" }, + {120, "freestyle", "Freestyle" }, + {121, "duet", "Duet" }, + {122, "punkrock", "Punk Rock" }, + {123, "drumsolo", "Drum Solo" }, + {124, "acapella", "A capella" }, + {125, "eurohouse", "Euro-House" }, + {126, "dancehall", "Dance Hall" }, + {255, "none", "none" }, + + {0, "undefined" } // must be last +}; + +@interface MP42Metadata (Private) + +- (void)readMetaDataFromFileHandle:(MP4FileHandle)fileHandle; + +@end + +@implementation MP42Metadata + +- (instancetype)init +{ + if ((self = [super init])) + { + presetName = @"Unnamed Set"; + sourceURL = nil; + tagsDict = [[NSMutableDictionary alloc] init]; + artworks = [[NSMutableArray alloc] init]; + isEdited = NO; + isArtworkEdited = NO; + } + + return self; +} + +- (instancetype)initWithSourceURL:(NSURL *)URL fileHandle:(MP4FileHandle)fileHandle +{ + if ((self = [super init])) + { + sourceURL = URL; + tagsDict = [[NSMutableDictionary alloc] init]; + artworks = [[NSMutableArray alloc] init]; + + [self readMetaDataFromFileHandle: fileHandle]; + isEdited = NO; + isArtworkEdited = NO; + } + + return self; +} + +- (instancetype)initWithFileURL:(NSURL *)URL; +{ + if ((self = [super init])) + { + sourceURL = URL; + tagsDict = [[NSMutableDictionary alloc] init]; + artworks = [[NSMutableArray alloc] init]; + + isEdited = NO; + isArtworkEdited = NO; + + NSError *error; + MP42XMLReader *xmlReader = [[MP42XMLReader alloc] initWithURL:URL error:&error]; + [self mergeMetadata:[xmlReader mMetadata]]; + [xmlReader release]; + } + + return self; +} + +- (NSString *)stringFromArray:(NSArray *)array +{ + NSString *result = [NSString string]; + for (NSDictionary* name in array) { + if ([result length]) + result = [result stringByAppendingString:@", "]; + result = [result stringByAppendingString:[name valueForKey:@"name"]]; + } + return result; +} + +- (NSArray *) dictArrayFromString:(NSString *)data +{ + NSString *splitElements = @",\\s*+"; + NSArray *stringArray = [data componentsSeparatedByRegex:splitElements]; + NSMutableArray *dictElements = [[[NSMutableArray alloc] init] autorelease]; + for (NSString *name in stringArray) { + [dictElements addObject:[NSDictionary dictionaryWithObject:name forKey:@"name"]]; + } + return dictElements; +} + +- (NSArray *) availableMetadata +{ + return [NSArray arrayWithObjects: + @"Name", + @"Artist", + @"Album Artist", + @"Album", + @"Grouping", + @"Composer", + @"Comments", + @"Genre", + @"Release Date", + @"Track #", + @"Disk #", + @"Tempo", + @"TV Show", + @"TV Episode #", + @"TV Network", + @"TV Episode ID", + @"TV Season", + @"Description", + @"Long Description", + @"Series Description", + @"Rating", + @"Rating Annotation", + @"Studio", + @"Cast", + @"Director", + @"Codirector", + @"Producers", + @"Screenwriters", + @"Lyrics", + @"Copyright", + @"Encoding Tool", + @"Encoded By", + @"Keywords", + @"Category", + @"contentID", + @"artistID", + @"playlistID", + @"genreID", + @"composerID", + @"XID", + @"iTunes Account", + @"iTunes Account Type", + @"iTunes Country", + @"Track Sub-Title", + @"Song Description", + @"Art Director", + @"Arranger", + @"Lyricist", + @"Acknowledgement", + @"Conductor", + @"Linear Notes", + @"Record Company", + @"Original Artist", + @"Phonogram Rights", + @"Producer", + @"Performer", + @"Publisher", + @"Sound Engineer", + @"Soloist", + @"Credits", + @"Thanks", + @"Online Extras", + @"Executive Producer", + @"Sort Name", + @"Sort Artist", + @"Sort Album Artist", + @"Sort Album", + @"Sort Composer", + @"Sort TV Show", nil]; +} + +- (NSArray *) writableMetadata +{ + return [NSArray arrayWithObjects: + @"Name", + @"Artist", + @"Album Artist", + @"Album", + @"Grouping", + @"Composer", + @"Comments", + @"Genre", + @"Release Date", + @"Track #", + @"Disk #", + @"Tempo", + @"TV Show", + @"TV Episode #", + @"TV Network", + @"TV Episode ID", + @"TV Season", + @"Description", + @"Long Description", + @"Series Description", + @"Rating", + @"Rating Annotation", + @"Studio", + @"Cast", + @"Director", + @"Codirector", + @"Producers", + @"Screenwriters", + @"Lyrics", + @"Copyright", + @"Encoding Tool", + @"Encoded By", + @"Keywords", + @"Category", + @"contentID", + @"artistID", + @"playlistID", + @"genreID", + @"composerID", + @"XID", + @"iTunes Account", + @"iTunes Account Type", + @"iTunes Country", + @"Track Sub-Title", + @"Song Description", + @"Art Director", + @"Arranger", + @"Lyricist", + @"Acknowledgement", + @"Conductor", + @"Linear Notes", + @"Record Company", + @"Original Artist", + @"Phonogram Rights", + @"Producer", + @"Performer", + @"Publisher", + @"Sound Engineer", + @"Soloist", + @"Credits", + @"Thanks", + @"Online Extras", + @"Executive Producer", + @"Sort Name", + @"Sort Artist", + @"Sort Album Artist", + @"Sort Album", + @"Sort Composer", + @"Sort TV Show", nil]; +} + +- (BOOL) setMediaKindFromString:(NSString *)mediaKindString; +{ + mediaKind_t *mediaKindList; + for (mediaKindList = (mediaKind_t*) mediaKind_strings; mediaKindList->english_name; mediaKindList++) { + if ([mediaKindString isEqualToString:mediaKindList->english_name]) { + mediaKind = mediaKindList->stik; + return YES; + } + } + return NO; +} + +- (BOOL) setContentRatingFromString:(NSString *)contentRatingString; +{ + contentRating_t *contentRatingList; + for ( contentRatingList = (contentRating_t*) contentRating_strings; contentRatingList->english_name; contentRatingList++) { + if ([contentRatingString isEqualToString:contentRatingList->english_name]) { + contentRating = contentRatingList->rtng; + return YES; + } + } + return NO; +} + +- (BOOL) setArtworkFromFilePath:(NSString *)imageFilePath; +{ + if(imageFilePath != nil && [imageFilePath length] > 0) { + NSImage *artworkImage = nil; + artworkImage = [[NSImage alloc] initByReferencingFile:imageFilePath]; + if([artworkImage isValid]) { + MP42Image *artwork = [[MP42Image alloc] initWithImage:artworkImage]; + [artworks addObject:artwork]; + [artworkImage release]; + [artwork release]; + isEdited =YES; + isArtworkEdited = YES; + return YES; + } else { + [artworkImage release]; + return NO; + } + } else { + [artworks release]; + artworks = nil; + isEdited =YES; + isArtworkEdited = YES; + return YES; + } +} + +- (NSString *) genreFromIndex: (NSInteger)index { + if ((index >= 0 && index < 127) || index == 255) { + genreType_t *genre = (genreType_t*) genreType_strings; + genre += index - 1; + return [NSString stringWithUTF8String:genre->english_name]; + } + else return nil; +} + +- (NSInteger) genreIndexFromString: (NSString *)genreString { + NSInteger genreIndex = 0; + genreType_t *genreList; + NSInteger k = 0; + for ( genreList = (genreType_t*) genreType_strings; genreList->english_name; genreList++, k++ ) { + if ([genreString isEqualToString:[NSString stringWithUTF8String:genreList->english_name]]) + genreIndex = k + 1; + } + return genreIndex; +} + +- (NSArray *) availableGenres +{ + return [NSArray arrayWithObjects: @"Animation", @"Classic TV", @"Comedy", @"Drama", + @"Fitness & Workout", @"Kids", @"Non-Fiction", @"Reality TV", @"Sci-Fi & Fantasy", + @"Sports", nil]; +} + +- (void) removeTagForKey:(NSString *)aKey +{ + [tagsDict removeObjectForKey:aKey]; + isEdited = YES; +} + +- (BOOL) setTag:(id)value forKey:(NSString *)key; +{ + BOOL noErr = YES; + NSString *regexPositive = @"YES|Yes|yes|1|2"; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + + if ([value isKindOfClass:[NSNull class]]) { + [tagsDict removeObjectForKey:key]; + return YES; + } + + if ([key isEqualToString:@"HD Video"]) { + if ([value isKindOfClass:[NSNumber class]]) + hdVideo = [value integerValue]; + else if( value != nil && [value length] > 0 && [value isMatchedByRegex:regexPositive]) + hdVideo = [value integerValue]; + else + hdVideo = 0; + + isEdited = YES; + } + else if ([key isEqualToString:@"Genre"]) { + if ([value isKindOfClass:[NSNumber class]]) { + [tagsDict setValue:[self genreFromIndex:[value integerValue]] forKey:key]; + isEdited = YES; + } + else if ([value isKindOfClass:[NSData class]]) { + if ([value length] >= 2) { + uint8_t* bytes = (uint8_t*)malloc([value length]); + memcpy(bytes, [value bytes], [value length]); + int genre = ((bytes[0]) << 8) + | ((bytes[1]) ); + + free(bytes); + [tagsDict setValue:[self genreFromIndex:genre] forKey:key]; + isEdited = YES; + } + } + else { + [tagsDict setValue:value forKey:key]; + isEdited = YES; + } + } + else if ([key isEqualToString:@"Gapless"]) { + if ([value isKindOfClass:[NSNumber class]]) { + gapless = [value integerValue]; + isEdited = YES; + } + else if( value != nil && [value length] > 0 && [value isMatchedByRegex:regexPositive]) { + gapless = 1; + isEdited = YES; + } + else { + gapless = 0; + isEdited = YES; + } + } + else if ([key isEqualToString:@"Track #"]) { + isEdited = YES; + if ([value isKindOfClass:[NSData class]]) { + uint8_t* bytes = (uint8_t*)malloc([value length]); + memcpy(bytes, [value bytes], [value length]); + int index = ((bytes[2]) << 8) + | ((bytes[3]) ); + int total = ((bytes[4]) << 8) + | ((bytes[5]) ); + + free(bytes); + NSString *trackN = [NSString stringWithFormat:@"%d/%d", index, total]; + [tagsDict setValue:trackN forKey:key]; + } + else { + [tagsDict setValue:value forKey:key]; + } + } + else if ([key isEqualToString:@"Disk #"]) { + isEdited = YES; + if ([value isKindOfClass:[NSData class]]) { + uint8_t* bytes = (uint8_t*)malloc([value length]); + memcpy(bytes, [value bytes], [value length]); + int index = ((bytes[2]) << 8) + | ((bytes[3]) ); + int total = ((bytes[4]) << 8) + | ((bytes[5]) ); + + free(bytes); + NSString *diskN = [NSString stringWithFormat:@"%d/%d", index, total]; + [tagsDict setValue:diskN forKey:key]; + } + else { + [tagsDict setValue:value forKey:key]; + } + } + else if ([key isEqualToString:@"Content Rating"]) { + isEdited = YES; + if ([value isKindOfClass:[NSNumber class]]) { + contentRating = [value integerValue]; + } + else + [self setContentRatingFromString:value]; + + } + else if ([key isEqualToString:@"Media Kind"]) { + isEdited = YES; + if ([value isKindOfClass:[NSNumber class]]) { + mediaKind = [value integerValue]; + } + else + [self setMediaKindFromString:value]; + } + else if ([key isEqualToString:@"Artwork"]) { + [self setArtworkFromFilePath:value]; + } + else if (![[tagsDict valueForKey:key] isEqualTo:value]) { + [tagsDict setValue:value forKey:key]; + isEdited = YES; + } + else + noErr = NO; + + [pool release]; + return noErr; +} + +- (NSString *) stringFromMetadata:(const char*)cString { + NSString *string; + + if ((string = [NSString stringWithCString:cString encoding: NSUTF8StringEncoding])) + return string; + + if ((string = [NSString stringWithCString:cString encoding: NSASCIIStringEncoding])) + return string; + + if ((string = [NSString stringWithCString:cString encoding: NSUTF16StringEncoding])) + return string; + + return @""; +} + +-(void) readMetaDataFromFileHandle:(MP4FileHandle)sourceHandle +{ + const MP4Tags* tags = MP4TagsAlloc(); + MP4TagsFetch( tags, sourceHandle ); + + if (tags->name) + [tagsDict setObject:[self stringFromMetadata:tags->name] + forKey:@"Name"]; + + if (tags->artist) + [tagsDict setObject:[self stringFromMetadata:tags->artist] + forKey:@"Artist"]; + + if (tags->albumArtist) + [tagsDict setObject:[self stringFromMetadata:tags->albumArtist] + forKey:@"Album Artist"]; + + if (tags->album) + [tagsDict setObject:[self stringFromMetadata:tags->album] + forKey:@"Album"]; + + if (tags->grouping) + [tagsDict setObject:[self stringFromMetadata:tags->grouping] + forKey:@"Grouping"]; + + if (tags->composer) + [tagsDict setObject:[self stringFromMetadata:tags->composer] + forKey:@"Composer"]; + + if (tags->comments) + [tagsDict setObject:[self stringFromMetadata:tags->comments] + forKey:@"Comments"]; + + if (tags->genre) + [tagsDict setObject:[self stringFromMetadata:tags->genre] + forKey:@"Genre"]; + + if (tags->genreType && !tags->genre) { + [tagsDict setObject:[self genreFromIndex:*tags->genreType] + forKey:@"Genre"]; + } + + if (tags->releaseDate) + [tagsDict setObject:[self stringFromMetadata:tags->releaseDate] + forKey:@"Release Date"]; + + if (tags->track) + [tagsDict setObject:[NSString stringWithFormat:@"%d/%d", tags->track->index, tags->track->total] + forKey:@"Track #"]; + + if (tags->disk) + [tagsDict setObject:[NSString stringWithFormat:@"%d/%d", tags->disk->index, tags->disk->total] + forKey:@"Disk #"]; + + if (tags->tempo) + [tagsDict setObject:[NSString stringWithFormat:@"%d", *tags->tempo] + forKey:@"Tempo"]; + + if (tags->trackSubTitle) + [tagsDict setObject:[self stringFromMetadata:tags->trackSubTitle] + forKey:@"Track Sub-Title"]; + + if (tags->songDescription) + [tagsDict setObject:[self stringFromMetadata:tags->songDescription] + forKey:@"Song Description"]; + + if (tags->artDirector) + [tagsDict setObject:[self stringFromMetadata:tags->artDirector] + forKey:@"Art Director"]; + + if (tags->arranger) + [tagsDict setObject:[self stringFromMetadata:tags->arranger] + forKey:@"Arranger"]; + + if (tags->lyricist) + [tagsDict setObject:[self stringFromMetadata:tags->lyricist] + forKey:@"Lyricist"]; + + if (tags->acknowledgement) + [tagsDict setObject:[self stringFromMetadata:tags->acknowledgement] + forKey:@"Acknowledgement"]; + + if (tags->conductor) + [tagsDict setObject:[self stringFromMetadata:tags->conductor] + forKey:@"Conductor"]; + + if (tags->linearNotes) + [tagsDict setObject:[self stringFromMetadata:tags->linearNotes] + forKey:@"Linear Notes"]; + + if (tags->recordCompany) + [tagsDict setObject:[self stringFromMetadata:tags->recordCompany] + forKey:@"Record Company"]; + + if (tags->originalArtist) + [tagsDict setObject:[self stringFromMetadata:tags->originalArtist] + forKey:@"Original Artist"]; + + if (tags->phonogramRights) + [tagsDict setObject:[self stringFromMetadata:tags->phonogramRights] + forKey:@"Phonogram Rights"]; + + if (tags->producer) + [tagsDict setObject:[self stringFromMetadata:tags->producer] + forKey:@"Producer"]; + + if (tags->performer) + [tagsDict setObject:[self stringFromMetadata:tags->performer] + forKey:@"Performer"]; + + if (tags->publisher) + [tagsDict setObject:[self stringFromMetadata:tags->publisher] + forKey:@"Publisher"]; + + if (tags->soundEngineer) + [tagsDict setObject:[self stringFromMetadata:tags->soundEngineer] + forKey:@"Sound Engineer"]; + + if (tags->soloist) + [tagsDict setObject:[self stringFromMetadata:tags->soloist] + forKey:@"Soloist"]; + + if (tags->credits) + [tagsDict setObject:[self stringFromMetadata:tags->credits] + forKey:@"Credits"]; + + if (tags->thanks) + [tagsDict setObject:[self stringFromMetadata:tags->thanks] + forKey:@"Thanks"]; + + if (tags->onlineExtras) + [tagsDict setObject:[self stringFromMetadata:tags->onlineExtras] + forKey:@"Online Extras"]; + + if (tags->executiveProducer) + [tagsDict setObject:[self stringFromMetadata:tags->executiveProducer] + forKey:@"Executive Producer"]; + + if (tags->tvShow) + [tagsDict setObject:[self stringFromMetadata:tags->tvShow] + forKey:@"TV Show"]; + + if (tags->tvEpisodeID) + [tagsDict setObject:[self stringFromMetadata:tags->tvEpisodeID] + forKey:@"TV Episode ID"]; + + if (tags->tvSeason) + [tagsDict setObject:[NSString stringWithFormat:@"%d", *tags->tvSeason] + forKey:@"TV Season"]; + + if (tags->tvEpisode) + [tagsDict setObject:[NSString stringWithFormat:@"%d", *tags->tvEpisode] + forKey:@"TV Episode #"]; + + if (tags->tvNetwork) + [tagsDict setObject:[self stringFromMetadata:tags->tvNetwork] + forKey:@"TV Network"]; + + if (tags->description) + [tagsDict setObject:[self stringFromMetadata:tags->description] + forKey:@"Description"]; + + if (tags->longDescription) + [tagsDict setObject:[self stringFromMetadata:tags->longDescription] + forKey:@"Long Description"]; + + if (tags->seriesDescription) + [tagsDict setObject:[self stringFromMetadata:tags->seriesDescription] + forKey:@"Series Description"]; + + if (tags->lyrics) + [tagsDict setObject:[self stringFromMetadata:tags->lyrics] + forKey:@"Lyrics"]; + + if (tags->copyright) + [tagsDict setObject:[self stringFromMetadata:tags->copyright] + forKey:@"Copyright"]; + + if (tags->encodingTool) + [tagsDict setObject:[self stringFromMetadata:tags->encodingTool] + forKey:@"Encoding Tool"]; + + if (tags->encodedBy) + [tagsDict setObject:[self stringFromMetadata:tags->encodedBy] + forKey:@"Encoded By"]; + + if (tags->hdVideo) + hdVideo = *tags->hdVideo; + + if (tags->mediaType) + mediaKind = *tags->mediaType; + + if (tags->contentRating) + contentRating = *tags->contentRating; + + if (tags->gapless) + gapless = *tags->gapless; + + if (tags->purchaseDate) + [tagsDict setObject:[self stringFromMetadata:tags->purchaseDate] + forKey:@"Purchase Date"]; + + if (tags->iTunesAccount) + [tagsDict setObject:[self stringFromMetadata:tags->iTunesAccount] + forKey:@"iTunes Account"]; + + if( tags->iTunesAccountType ) + [tagsDict setObject:[NSString stringWithFormat:@"%d", *tags->iTunesAccountType] + forKey:@"iTunes Account Type"]; + + if (tags->iTunesCountry) + [tagsDict setObject:[NSString stringWithFormat:@"%d", *tags->iTunesCountry] + forKey:@"iTunes Country"]; + + if (tags->contentID) + [tagsDict setObject:[NSString stringWithFormat:@"%d", *tags->contentID] + forKey:@"contentID"]; + + if (tags->artistID) + [tagsDict setObject:[NSString stringWithFormat:@"%d", *tags->artistID] + forKey:@"artistID"]; + + if (tags->playlistID) + [tagsDict setObject:[NSString stringWithFormat:@"%lld", *tags->playlistID] + forKey:@"playlistID"]; + + if (tags->genreID) + [tagsDict setObject:[NSString stringWithFormat:@"%d", *tags->genreID] + forKey:@"genreID"]; + + if (tags->composerID) + [tagsDict setObject:[NSString stringWithFormat:@"%d", *tags->composerID] + forKey:@"composerID"]; + + if (tags->xid) + [tagsDict setObject:[self stringFromMetadata:tags->xid] + forKey:@"XID"]; + + if (tags->sortName) + [tagsDict setObject:[self stringFromMetadata:tags->sortName] + forKey:@"Sort Name"]; + + if (tags->sortArtist) + [tagsDict setObject:[self stringFromMetadata:tags->sortArtist] + forKey:@"Sort Artist"]; + + if (tags->sortAlbumArtist) + [tagsDict setObject:[self stringFromMetadata:tags->sortAlbumArtist] + forKey:@"Sort Album Artist"]; + + if (tags->sortAlbum) + [tagsDict setObject:[self stringFromMetadata:tags->sortAlbum] + forKey:@"Sort Album"]; + + if (tags->sortComposer) + [tagsDict setObject:[self stringFromMetadata:tags->sortComposer] + forKey:@"Sort Composer"]; + + if (tags->sortTVShow) + [tagsDict setObject:[self stringFromMetadata:tags->sortTVShow] + forKey:@"Sort TV Show"]; + + if (tags->podcast) + podcast = *tags->podcast; + + if (tags->keywords) + [tagsDict setObject:[self stringFromMetadata:tags->keywords] + forKey:@"Keywords"]; + + if (tags->category) + [tagsDict setObject:[self stringFromMetadata:tags->category] + forKey:@"Category"]; + + if (tags->artwork) { + uint32_t i; + for (i = 0; i < tags->artworkCount; i++) { + MP42Image *artwork = [[MP42Image alloc] initWithBytes:tags->artwork[i].data length:tags->artwork[i].size type:tags->artwork[i].type]; + [artworks addObject:artwork]; + [artwork release]; + } + } + + MP4TagsFree(tags); + + /* read the remaining iTMF items */ + MP4ItmfItemList* list = MP4ItmfGetItemsByMeaning(sourceHandle, "com.apple.iTunes", "iTunEXTC"); + if (list) { + uint32_t i; + for (i = 0; i < list->size; i++) { + MP4ItmfItem* item = &list->elements[i]; + uint32_t j; + for (j = 0; j < item->dataList.size; j++) { + MP4ItmfData* data = &item->dataList.elements[j]; + NSString *ratingString = [[NSString alloc] initWithBytes:data->value length: data->valueSize encoding:NSUTF8StringEncoding]; + NSString *splitElements = @"\\|"; + NSArray *ratingItems = [ratingString componentsSeparatedByRegex:splitElements]; + [ratingString release]; + if ([ratingItems count] > 2) + ratingiTunesCode = [[NSString stringWithFormat:@"%@|%@|%@|",[ratingItems objectAtIndex:0], [ratingItems objectAtIndex:1], [ratingItems objectAtIndex:2]] retain]; + else + ratingiTunesCode = nil; + + [tagsDict setObject:[NSNumber numberWithUnsignedInteger:[[SBRatings defaultManager] ratingIndexForiTunesCode:ratingiTunesCode]] forKey:@"Rating"]; + if ([ratingItems count] >= 4) + [tagsDict setObject:[ratingItems objectAtIndex:3] forKey:@"Rating Annotation"]; + } + } + MP4ItmfItemListFree(list); + } + + list = MP4ItmfGetItemsByMeaning(sourceHandle, "com.apple.iTunes", "iTunMOVI"); + if (list) { + uint32_t i; + for (i = 0; i < list->size; i++) { + MP4ItmfItem* item = &list->elements[i]; + uint32_t j; + for(j = 0; j < item->dataList.size; j++) { + MP4ItmfData* data = &item->dataList.elements[j]; + NSData *xmlData = [NSData dataWithBytes:data->value length:data->valueSize]; + NSDictionary *dma = (NSDictionary *)[NSPropertyListSerialization + propertyListFromData:xmlData + mutabilityOption:NSPropertyListMutableContainersAndLeaves + format:nil + errorDescription:nil]; + + NSString *tag; + if ([tag = [self stringFromArray:[dma valueForKey:@"cast"]] length]) + [tagsDict setObject:tag forKey:@"Cast"]; + if ([tag = [self stringFromArray:[dma valueForKey:@"directors"]] length]) + [tagsDict setObject:tag forKey:@"Director"]; + if ([tag = [self stringFromArray:[dma valueForKey:@"codirectors"]] length]) + [tagsDict setObject:tag forKey:@"Codirector"]; + if ([tag = [self stringFromArray:[dma valueForKey:@"producers"]] length]) + [tagsDict setObject:tag forKey:@"Producers"]; + if ([tag = [self stringFromArray:[dma valueForKey:@"screenwriters"]] length]) + [tagsDict setObject:tag forKey:@"Screenwriters"]; + if ([tag = [dma valueForKey:@"studio"] length]) + [tagsDict setObject:tag forKey:@"Studio"]; + } + } + MP4ItmfItemListFree(list); + } +} + +- (BOOL) writeMetadataWithFileHandle: (MP4FileHandle *)fileHandle +{ + if (!fileHandle) + return NO; + + const MP4Tags* tags = MP4TagsAlloc(); + + MP4TagsFetch(tags, fileHandle); + + MP4TagsSetName(tags, [[tagsDict valueForKey:@"Name"] UTF8String]); + + MP4TagsSetArtist(tags, [[tagsDict valueForKey:@"Artist"] UTF8String]); + + MP4TagsSetAlbumArtist(tags, [[tagsDict valueForKey:@"Album Artist"] UTF8String]); + + MP4TagsSetAlbum(tags, [[tagsDict valueForKey:@"Album"] UTF8String]); + + MP4TagsSetGrouping(tags, [[tagsDict valueForKey:@"Grouping"] UTF8String]); + + MP4TagsSetComposer(tags, [[tagsDict valueForKey:@"Composer"] UTF8String]); + + MP4TagsSetComments(tags, [[tagsDict valueForKey:@"Comments"] UTF8String]); + + uint16_t genreType = [self genreIndexFromString:[tagsDict valueForKey:@"Genre"]]; + if (genreType) { + MP4TagsSetGenre(tags, NULL); + MP4TagsSetGenreType(tags, &genreType); + } + else { + MP4TagsSetGenreType(tags, NULL); + MP4TagsSetGenre(tags, [[tagsDict valueForKey:@"Genre"] UTF8String]); + } + + MP4TagsSetReleaseDate(tags, [[tagsDict valueForKey:@"Release Date"] UTF8String]); + + if ([tagsDict valueForKey:@"Track #"]) { + MP4TagTrack dtrack; int trackNum = 0, totalTrackNum = 0; + char separator; + sscanf([[tagsDict valueForKey:@"Track #"] UTF8String],"%u%[/- ]%u", &trackNum, &separator, &totalTrackNum); + dtrack.index = trackNum; + dtrack.total = totalTrackNum; + MP4TagsSetTrack(tags, &dtrack); + } + else + MP4TagsSetTrack(tags, NULL); + + if ([tagsDict valueForKey:@"Disk #"]) { + MP4TagDisk ddisk; int diskNum = 0, totalDiskNum = 0; + char separator; + sscanf([[tagsDict valueForKey:@"Disk #"] UTF8String],"%u%[/- ]%u", &diskNum, &separator, &totalDiskNum); + ddisk.index = diskNum; + ddisk.total = totalDiskNum; + MP4TagsSetDisk(tags, &ddisk); + } + else + MP4TagsSetDisk(tags, NULL); + + if ([tagsDict valueForKey:@"Tempo"]) { + const uint16_t i = [[tagsDict valueForKey:@"Tempo"] integerValue]; + MP4TagsSetTempo(tags, &i); + } + else + MP4TagsSetTempo(tags, NULL); + + MP4TagsSetTrackSubTitle(tags, [[tagsDict valueForKey:@"Track Sub-Title"] UTF8String]); + + MP4TagsSetSongDescription(tags, [[tagsDict valueForKey:@"Song Description"] UTF8String]); + + MP4TagsSetArtDirector(tags, [[tagsDict valueForKey:@"Art Director"] UTF8String]); + + MP4TagsSetArranger(tags, [[tagsDict valueForKey:@"Arranger"] UTF8String]); + + MP4TagsSetLyricist(tags, [[tagsDict valueForKey:@"Lyricist"] UTF8String]); + + MP4TagsSetAcknowledgement(tags, [[tagsDict valueForKey:@"Acknowledgement"] UTF8String]); + + MP4TagsSetConductor(tags, [[tagsDict valueForKey:@"Conductor"] UTF8String]); + + MP4TagsSetLinearNotes(tags, [[tagsDict valueForKey:@"Linear Notes"] UTF8String]); + + MP4TagsSetRecordCompany(tags, [[tagsDict valueForKey:@"Record Company"] UTF8String]); + + MP4TagsSetOriginalArtist(tags, [[tagsDict valueForKey:@"Original Artist"] UTF8String]); + + MP4TagsSetPhonogramRights(tags, [[tagsDict valueForKey:@"Phonogram Rights"] UTF8String]); + + MP4TagsSetProducer(tags, [[tagsDict valueForKey:@"Producer"] UTF8String]); + + MP4TagsSetPerformer(tags, [[tagsDict valueForKey:@"Performer"] UTF8String]); + + MP4TagsSetPublisher(tags, [[tagsDict valueForKey:@"Publisher"] UTF8String]); + + MP4TagsSetSoundEngineer(tags, [[tagsDict valueForKey:@"Sound Engineer"] UTF8String]); + + MP4TagsSetSoloist(tags, [[tagsDict valueForKey:@"Soloist"] UTF8String]); + + MP4TagsSetCredits(tags, [[tagsDict valueForKey:@"Credits"] UTF8String]); + + MP4TagsSetThanks(tags, [[tagsDict valueForKey:@"Thanks"] UTF8String]); + + MP4TagsSetOnlineExtras(tags, [[tagsDict valueForKey:@"Online Extras"] UTF8String]); + + MP4TagsSetExecutiveProducer(tags, [[tagsDict valueForKey:@"Executive Producer"] UTF8String]); + + MP4TagsSetTVShow(tags, [[tagsDict valueForKey:@"TV Show"] UTF8String]); + + MP4TagsSetTVNetwork(tags, [[tagsDict valueForKey:@"TV Network"] UTF8String]); + + MP4TagsSetTVEpisodeID(tags, [[tagsDict valueForKey:@"TV Episode ID"] UTF8String]); + + if ([tagsDict valueForKey:@"TV Season"]) { + const uint32_t i = [[tagsDict valueForKey:@"TV Season"] intValue]; + MP4TagsSetTVSeason(tags, &i); + } + else + MP4TagsSetTVSeason(tags, NULL); + + if ([tagsDict valueForKey:@"TV Episode #"]) { + const uint32_t i = [[tagsDict valueForKey:@"TV Episode #"] intValue]; + MP4TagsSetTVEpisode(tags, &i); + } + else + MP4TagsSetTVEpisode(tags, NULL); + + MP4TagsSetDescription(tags, [[tagsDict valueForKey:@"Description"] UTF8String]); + + MP4TagsSetLongDescription(tags, [[tagsDict valueForKey:@"Long Description"] UTF8String]); + + MP4TagsSetSeriesDescription(tags, [[tagsDict valueForKey:@"Series Description"] UTF8String]); + + MP4TagsSetLyrics(tags, [[tagsDict valueForKey:@"Lyrics"] UTF8String]); + + MP4TagsSetCopyright(tags, [[tagsDict valueForKey:@"Copyright"] UTF8String]); + + MP4TagsSetEncodingTool(tags, [[tagsDict valueForKey:@"Encoding Tool"] UTF8String]); + + MP4TagsSetEncodedBy(tags, [[tagsDict valueForKey:@"Encoded By"] UTF8String]); + + MP4TagsSetPurchaseDate(tags, [[tagsDict valueForKey:@"Purchase Date"] UTF8String]); + + MP4TagsSetITunesAccount(tags, [[tagsDict valueForKey:@"iTunes Account"] UTF8String]); + + if (mediaKind != 0) + MP4TagsSetMediaType(tags, &mediaKind); + else + MP4TagsSetMediaType(tags, NULL); + + if (mediaKind == 21) { + const uint8_t n = 1; + MP4TagsSetPodcast(tags, &n); + } + else + MP4TagsSetPodcast(tags, NULL); + + if (mediaKind == 23) { + const uint8_t n = 1; + MP4TagsSetITunesU(tags, &n); + } + else + MP4TagsSetITunesU(tags, NULL); + + if(hdVideo) + MP4TagsSetHDVideo(tags, &hdVideo); + else + MP4TagsSetHDVideo(tags, NULL); + + if(gapless) + MP4TagsSetGapless(tags, &gapless); + else + MP4TagsSetGapless(tags, NULL); + + if(podcast) + MP4TagsSetPodcast(tags, &podcast); + else + MP4TagsSetPodcast(tags, NULL); + + MP4TagsSetKeywords(tags, [[tagsDict valueForKey:@"Keywords"] UTF8String]); + + MP4TagsSetCategory(tags, [[tagsDict valueForKey:@"Category"] UTF8String]); + + MP4TagsSetContentRating(tags, &contentRating); + + if ([tagsDict valueForKey:@"iTunes Country"]) { + const uint32_t i = [[tagsDict valueForKey:@"iTunes Country"] integerValue]; + MP4TagsSetITunesCountry(tags, &i); + } + else + MP4TagsSetITunesCountry(tags, NULL); + + if ([tagsDict valueForKey:@"contentID"]) { + const uint32_t i = [[tagsDict valueForKey:@"contentID"] integerValue]; + MP4TagsSetContentID(tags, &i); + } + else + MP4TagsSetContentID(tags, NULL); + + if ([tagsDict valueForKey:@"genreID"]) { + const uint32_t i = [[tagsDict valueForKey:@"genreID"] integerValue]; + MP4TagsSetGenreID(tags, &i); + } + else + MP4TagsSetGenreID(tags, NULL); + + if ([tagsDict valueForKey:@"artistID"]) { + const uint32_t i = [[tagsDict valueForKey:@"artistID"] integerValue]; + MP4TagsSetArtistID(tags, &i); + } + else + MP4TagsSetArtistID(tags, NULL); + + if ([tagsDict valueForKey:@"playlistID"]) { + const uint64_t i = [[tagsDict valueForKey:@"playlistID"] integerValue]; + MP4TagsSetPlaylistID(tags, &i); + } + else + MP4TagsSetPlaylistID(tags, NULL); + + if ([tagsDict valueForKey:@"composerID"]) { + const uint32_t i = [[tagsDict valueForKey:@"composerID"] integerValue]; + MP4TagsSetComposerID(tags, &i); + } + else + MP4TagsSetComposerID(tags, NULL); + + MP4TagsSetXID(tags, [[tagsDict valueForKey:@"XID"] UTF8String]); + + MP4TagsSetSortName(tags, [[tagsDict valueForKey:@"Sort Name"] UTF8String]); + + MP4TagsSetSortArtist(tags, [[tagsDict valueForKey:@"Sort Artist"] UTF8String]); + + MP4TagsSetSortAlbumArtist(tags, [[tagsDict valueForKey:@"Sort Album Artist"] UTF8String]); + + MP4TagsSetSortAlbum(tags, [[tagsDict valueForKey:@"Sort Album"] UTF8String]); + + MP4TagsSetSortComposer(tags, [[tagsDict valueForKey:@"Sort Composer"] UTF8String]); + + MP4TagsSetSortTVShow(tags, [[tagsDict valueForKey:@"Sort TV Show"] UTF8String]); + + + if (isArtworkEdited) { + uint32_t j; + for (j = 0; j < tags->artworkCount; j++) + MP4TagsRemoveArtwork(tags, j); + + if ([artworks count]) { + uint32_t i; + for (i = 0; i < [artworks count]; i++) { + MP42Image *artwork; + MP4TagArtwork newArtwork; + NSArray *representations; + NSData *bitmapData; + + artwork = [artworks objectAtIndex:i]; + if (artwork.data) { + newArtwork.data = (void *)[artwork.data bytes]; + newArtwork.size = [artwork.data length]; + newArtwork.type = artwork.type; + } + else { + representations = [artwork.image representations]; + bitmapData = [NSBitmapImageRep representationOfImageRepsInArray:representations + usingType:NSPNGFileType properties:nil]; + + newArtwork.data = (void *)[bitmapData bytes]; + newArtwork.size = [bitmapData length]; + newArtwork.type = MP4_ART_PNG; + } + + if (tags->artworkCount > i) + MP4TagsSetArtwork(tags, i, &newArtwork); + else + MP4TagsAddArtwork(tags, &newArtwork); + } + } + } + + MP4TagsStore(tags, fileHandle); + MP4TagsFree(tags); + + /* Rewrite extended metadata using the generic iTMF api */ + + if ([tagsDict valueForKey:@"Rating"]) { + MP4ItmfItemList* list = MP4ItmfGetItemsByMeaning(fileHandle, "com.apple.iTunes", "iTunEXTC"); + if (list) { + uint32_t i; + for (i = 0; i < list->size; i++) { + MP4ItmfItem* item = &list->elements[i]; + MP4ItmfRemoveItem(fileHandle, item); + } + } + MP4ItmfItemListFree(list); + + MP4ItmfItem* newItem = MP4ItmfItemAlloc( "----", 1 ); + newItem->mean = strdup( "com.apple.iTunes" ); + newItem->name = strdup( "iTunEXTC" ); + + MP4ItmfData* data = &newItem->dataList.elements[0]; + + if (![[tagsDict valueForKey:@"Rating"] isKindOfClass:[NSNumber class]] || + [[tagsDict valueForKey:@"Rating"] unsignedIntegerValue] == [[SBRatings defaultManager] unknownIndex]) { + if (!ratingiTunesCode) { + ratingiTunesCode = [[[SBRatings defaultManager] iTunesCodes] objectAtIndex:[[SBRatings defaultManager] unknownIndex]]; + } + } else { + ratingiTunesCode = [[[SBRatings defaultManager] iTunesCodes] objectAtIndex:[[tagsDict valueForKey:@"Rating"] unsignedIntegerValue]]; + } + NSString *ratingString = ratingiTunesCode; + if ([[tagsDict valueForKey:@"Rating Annotation"] length] && [ratingString length]) { + ratingString = [NSString stringWithFormat:@"%@%@", ratingString, [tagsDict valueForKey:@"Rating Annotation"]]; + } + data->typeCode = MP4_ITMF_BT_UTF8; + data->valueSize = strlen([ratingString UTF8String]); + data->value = (uint8_t*)malloc( data->valueSize ); + memcpy( data->value, [ratingString UTF8String], data->valueSize ); + + MP4ItmfAddItem(fileHandle, newItem); + MP4ItmfItemFree(newItem); + } + else { + MP4ItmfItemList* list = MP4ItmfGetItemsByMeaning(fileHandle, "com.apple.iTunes", "iTunEXTC"); + if (list) { + uint32_t i; + for (i = 0; i < list->size; i++) { + MP4ItmfItem* item = &list->elements[i]; + MP4ItmfRemoveItem(fileHandle, item); + } + } + MP4ItmfItemListFree(list); + } + + MP4ItmfItemList* list = MP4ItmfGetItemsByMeaning(fileHandle, "com.apple.iTunes", "iTunMOVI"); + NSMutableDictionary *iTunMovi = [[NSMutableDictionary alloc] init];; + if (list) { + uint32_t i; + for (i = 0; i < list->size; i++) { + MP4ItmfItem* item = &list->elements[i]; + uint32_t j; + for(j = 0; j < item->dataList.size; j++) { + MP4ItmfData* data = &item->dataList.elements[j]; + NSData *xmlData = [NSData dataWithBytes:data->value length:data->valueSize]; + NSDictionary *dma = (NSDictionary *)[NSPropertyListSerialization + propertyListFromData:xmlData + mutabilityOption:NSPropertyListMutableContainersAndLeaves + format:nil + errorDescription:nil]; + [iTunMovi release]; + iTunMovi = [dma mutableCopy]; + } + } + MP4ItmfItemListFree(list); + } + + if (iTunMovi) { + if ([tagsDict valueForKey:@"Cast"]) + [iTunMovi setObject:[self dictArrayFromString:[tagsDict valueForKey:@"Cast"]] forKey:@"cast"]; + else + [iTunMovi removeObjectForKey:@"cast"]; + + if ([tagsDict valueForKey:@"Director"]) + [iTunMovi setObject:[self dictArrayFromString:[tagsDict valueForKey:@"Director"]] forKey:@"directors"]; + else + [iTunMovi removeObjectForKey:@"directors"]; + + if ([tagsDict valueForKey:@"Codirector"]) + [iTunMovi setObject:[self dictArrayFromString:[tagsDict valueForKey:@"Codirector"]] forKey:@"codirectors"]; + else + [iTunMovi removeObjectForKey:@"codirectors"]; + + if ([tagsDict valueForKey:@"Producers"]) + [iTunMovi setObject:[self dictArrayFromString:[tagsDict valueForKey:@"Producers"]] forKey:@"producers"]; + else + [iTunMovi removeObjectForKey:@"producers"]; + + if ([tagsDict valueForKey:@"Screenwriters"]) + [iTunMovi setObject:[self dictArrayFromString:[tagsDict valueForKey:@"Screenwriters"]] forKey:@"screenwriters"]; + else + [iTunMovi removeObjectForKey:@"screenwriters"]; + + if ([tagsDict valueForKey:@"Studio"]) + [iTunMovi setObject:[tagsDict valueForKey:@"Studio"] forKey:@"studio"]; + else + [iTunMovi removeObjectForKey:@"studio"]; + + NSData *serializedPlist = [NSPropertyListSerialization + dataFromPropertyList:iTunMovi + format:NSPropertyListXMLFormat_v1_0 + errorDescription:nil]; + if ([iTunMovi count]) { + MP4ItmfItemList* list = MP4ItmfGetItemsByMeaning(fileHandle, "com.apple.iTunes", "iTunMOVI"); + if (list) { + uint32_t i; + for (i = 0; i < list->size; i++) { + MP4ItmfItem* item = &list->elements[i]; + MP4ItmfRemoveItem(fileHandle, item); + } + } + MP4ItmfItemListFree(list); + + MP4ItmfItem* newItem = MP4ItmfItemAlloc( "----", 1 ); + newItem->mean = strdup( "com.apple.iTunes" ); + newItem->name = strdup( "iTunMOVI" ); + + MP4ItmfData* data = &newItem->dataList.elements[0]; + data->typeCode = MP4_ITMF_BT_UTF8; + data->valueSize = [serializedPlist length]; + data->value = (uint8_t*)malloc( data->valueSize ); + memcpy( data->value, [serializedPlist bytes], data->valueSize ); + + MP4ItmfAddItem(fileHandle, newItem); + MP4ItmfItemFree(newItem); + } + else { + MP4ItmfItemList* list = MP4ItmfGetItemsByMeaning(fileHandle, "com.apple.iTunes", "iTunMOVI"); + if (list) { + uint32_t i; + for (i = 0; i < list->size; i++) { + MP4ItmfItem* item = &list->elements[i]; + MP4ItmfRemoveItem(fileHandle, item); + } + } + MP4ItmfItemListFree(list); + } + } + + [iTunMovi release]; + + return YES; +} + +- (BOOL) mergeMetadata: (MP42Metadata *) newMetadata +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSString * tagValue; + + [newMetadata retain]; + + for (NSString * key in [self writableMetadata]) + if((tagValue = [newMetadata.tagsDict valueForKey:key])) + [tagsDict setObject:tagValue forKey:key]; + + for (NSImage *artwork in newMetadata.artworks) { + isArtworkEdited = YES; + [artworks addObject:artwork]; + } + + mediaKind = newMetadata.mediaKind; + contentRating = newMetadata.contentRating; + gapless = newMetadata.gapless; + hdVideo = newMetadata.hdVideo; + + isEdited = YES; + + [newMetadata release]; + + [pool release]; + + return YES; +} + +@synthesize presetName; + +@synthesize isEdited; + +@synthesize artworks; + +@synthesize isArtworkEdited; +@synthesize artworkThumbURLs; +@synthesize artworkFullsizeURLs; +@synthesize artworkProviderNames; + +@synthesize mediaKind; +@synthesize contentRating; +@synthesize hdVideo; +@synthesize gapless; +@synthesize podcast; + +@synthesize tagsDict; + + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [coder encodeInt:2 forKey:@"MP42TagEncodeVersion"]; + + [coder encodeObject:presetName forKey:@"MP42SetName"]; + [coder encodeObject:tagsDict forKey:@"MP42TagsDict"]; + [coder encodeObject:artworks forKey:@"MP42Artwork"]; + [coder encodeBool:isArtworkEdited forKey:@"MP42ArtworkEdited"]; + + [coder encodeInt:mediaKind forKey:@"MP42MediaKind"]; + [coder encodeInt:contentRating forKey:@"MP42ContentRating"]; + [coder encodeInt:hdVideo forKey:@"MP42HDVideo"]; + [coder encodeInt:gapless forKey:@"MP42Gapless"]; + [coder encodeInt:podcast forKey:@"MP42Podcast"]; + + [coder encodeBool:isEdited forKey:@"MP42Edited"]; +} + +- (id)initWithCoder:(NSCoder *)decoder +{ + self = [super init]; + + NSInteger version = [decoder decodeIntForKey:@"MP42TagEncodeVersion"]; + + presetName = [[decoder decodeObjectForKey:@"MP42SetName"] retain]; + tagsDict = [[decoder decodeObjectForKey:@"MP42TagsDict"] retain]; + + // Subler 0.19 and previous sets + if (version < 2) { + artworks = [[NSMutableArray alloc] init]; + id image = [decoder decodeObjectForKey:@"MP42Artwork"]; + if (image) { + MP42Image *artwork = [[MP42Image alloc] initWithImage:image]; + [artworks addObject: artwork]; + [artwork release]; + } + } + else + artworks = [[decoder decodeObjectForKey:@"MP42Artwork"] retain]; + + isArtworkEdited = [decoder decodeBoolForKey:@"MP42ArtworkEdited"]; + + mediaKind = [decoder decodeIntForKey:@"MP42MediaKind"]; + contentRating = [decoder decodeIntForKey:@"MP42ContentRating"]; + hdVideo = [decoder decodeIntForKey:@"MP42HDVideo"]; + gapless = [decoder decodeIntForKey:@"MP42Gapless"]; + podcast = [decoder decodeIntForKey:@"MP42Podcast"]; + + isEdited = [decoder decodeBoolForKey:@"MP42Edited"]; + + return self; +} + +- (id)copyWithZone:(NSZone *)zone +{ + MP42Metadata *newObject = [[MP42Metadata allocWithZone:zone] init]; + + if (presetName) + newObject.presetName = presetName; + + [newObject mergeMetadata:self]; + + newObject.contentRating = contentRating; + newObject.gapless = gapless; + newObject.hdVideo = hdVideo; + newObject.podcast = podcast; + + return newObject; +} + +-(void) dealloc +{ + [presetName release]; + + [artworks release]; + + [artworkThumbURLs release]; + [artworkFullsizeURLs release]; + [artworkProviderNames release]; + + [tagsDict release]; + [super dealloc]; +} + +@end diff --git a/MP42/MP42MkvImporter.h b/MP42/MP42MkvImporter.h new file mode 100644 index 0000000..a792451 --- /dev/null +++ b/MP42/MP42MkvImporter.h @@ -0,0 +1,19 @@ +// +// MP42MkvFileImporter.h +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import +#import "MP42FileImporter.h" + +@interface MP42MkvImporter : MP42FileImporter { + struct MatroskaFile *_matroskaFile; + struct StdIoStream *_ioStream; + + u_int64_t _fileDuration; +} + +@end \ No newline at end of file diff --git a/MP42/MP42MkvImporter.m b/MP42/MP42MkvImporter.m new file mode 100644 index 0000000..d0c2556 --- /dev/null +++ b/MP42/MP42MkvImporter.m @@ -0,0 +1,941 @@ +// +// MP42MkvFileImporter.m +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import "MP42MkvImporter.h" + +#import "MP42File.h" +#import "MP42SubUtilities.h" +#import "SBLanguages.h" + +#import "MatroskaParser.h" +#import "MatroskaFile.h" +#include "avutil.h" + +u_int32_t MP4AV_Ac3GetSamplingRate(u_int8_t* pHdr); + +@interface MatroskaSample : NSObject { +@public + unsigned long long startTime; + unsigned long long endTime; + unsigned long long filePos; + unsigned int frameSize; + unsigned int frameFlags; +} +@end + +@implementation MatroskaSample +@end + +@interface MatroskaDemuxHelper : NSObject { + @public + NSMutableArray *queue; + NSMutableArray *offsetsArray; + + NSMutableArray *samplesBuffer; + uint64_t current_time; + int64_t minDisplayOffset; + unsigned int buffer, samplesWritten, bufferFlush; + + MP42SampleBuffer *previousSample; + SBSubSerializer *ss; +} +@end + +@implementation MatroskaDemuxHelper + +- (id)init +{ + if ((self = [super init])) { + queue = [[NSMutableArray alloc] init]; + offsetsArray = [[NSMutableArray alloc] init]; + + samplesBuffer = [[NSMutableArray alloc] initWithCapacity:100]; + } + return self; +} + +- (void) dealloc { + [queue release], queue = nil; + [offsetsArray release], offsetsArray = nil; + [samplesBuffer release], samplesBuffer = nil; + [ss release], ss = nil; + + [super dealloc]; +} +@end + +int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t FilePos, uint8_t** frame, uint32_t *FrameSize) +{ + uint8_t *packet = NULL; + uint32_t iSize = *FrameSize; + + if (fseeko(ioStream->fp, FilePos, SEEK_SET)) { + fprintf(stderr,"fseeko(): %s\n", strerror(errno)); + return 0; + } + + if (trackInfo->CompMethodPrivateSize != 0) { + packet = malloc(iSize + trackInfo->CompMethodPrivateSize); + memcpy(packet, trackInfo->CompMethodPrivate, trackInfo->CompMethodPrivateSize); + } + else + packet = malloc(iSize); + + if (packet == NULL) { + fprintf(stderr,"Out of memory\n"); + return 0; + } + + size_t rd = fread(packet + trackInfo->CompMethodPrivateSize, 1, iSize, ioStream->fp); + if (rd != iSize) { + if (rd == 0) { + if (feof(ioStream->fp)) + fprintf(stderr,"Unexpected EOF while reading frame\n"); + else + fprintf(stderr,"Error reading frame: %s\n",strerror(errno)); + } else + fprintf(stderr,"Short read while reading audio frame\n"); + + free(packet); + return 0; + } + + iSize += trackInfo->CompMethodPrivateSize; + + if (trackInfo->CompEnabled) { + switch (trackInfo->CompMethod) { + case COMP_ZLIB: + if (!DecompressZlib(&packet, &iSize)) { + free(packet); + return 0; + } + break; + + case COMP_BZIP: + if (!DecompressBzlib(&packet, &iSize)) { + free(packet); + return 0; + } + break; + + // Not Implemented yet + case COMP_LZO1X: + break; + + default: + break; + } + } + + *frame = packet; + *FrameSize = iSize; + + return 1; +} + +@interface MP42MkvImporter () + - (MP42Metadata *)readMatroskaMetadata; + - (NSString *)matroskaCodecIDToHumanReadableName:(TrackInfo *)track; + - (NSString *)matroskaTrackName:(TrackInfo *)track; + - (uint64_t)matroskaTrackStartTime:(TrackInfo *)track Id:(MP4TrackId)Id; +@end + +@implementation MP42MkvImporter + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError +{ + if ((self = [super init])) { + _fileURL = [fileURL retain]; + + _ioStream = calloc(1, sizeof(StdIoStream)); + _matroskaFile= openMatroskaFile((char *)[[_fileURL path] UTF8String], _ioStream); + + if(!_matroskaFile) { + if (outError) + *outError = MP42Error(@"The movie could not be opened.", @"The file is not a matroska file.", 100); + + [self release]; + return nil; + } + + //SegmentInfo *info = mkv_GetFileInfo(matroskaFile); + uint64_t *trackSizes = [self copyGuessedTrackDataLength]; + + NSInteger trackCount = mkv_GetNumTracks(_matroskaFile); + _tracksArray = [[NSMutableArray alloc] initWithCapacity:trackCount]; + + NSInteger i; + + for (i = 0; i < trackCount; i++) { + TrackInfo *mkvTrack = mkv_GetTrackInfo(_matroskaFile, i); + MP42Track *newTrack = nil; + + // Video + if (mkvTrack->Type == TT_VIDEO) { + float trackWidth = 0; + newTrack = [[MP42VideoTrack alloc] init]; + + [(MP42VideoTrack*)newTrack setWidth:mkvTrack->AV.Video.PixelWidth]; + [(MP42VideoTrack*)newTrack setHeight:mkvTrack->AV.Video.PixelHeight]; + + AVRational dar, invPixelSize, sar; + dar = (AVRational){mkvTrack->AV.Video.DisplayWidth, mkvTrack->AV.Video.DisplayHeight}; + invPixelSize = (AVRational){mkvTrack->AV.Video.PixelHeight, mkvTrack->AV.Video.PixelWidth}; + sar = av_mul_q(dar, invPixelSize); + + av_reduce(&sar.num, &sar.den, sar.num, sar.den, fixed1); + + if (sar.num && sar.den) + trackWidth = mkvTrack->AV.Video.PixelWidth * sar.num / sar.den; + else + trackWidth = mkvTrack->AV.Video.PixelWidth; + + [(MP42VideoTrack*)newTrack setTrackWidth:trackWidth]; + [(MP42VideoTrack*)newTrack setTrackHeight:mkvTrack->AV.Video.PixelHeight]; + + [(MP42VideoTrack*)newTrack setHSpacing:sar.num]; + [(MP42VideoTrack*)newTrack setVSpacing:sar.den]; + } + + // Audio + else if (mkvTrack->Type == TT_AUDIO) { + newTrack = [[MP42AudioTrack alloc] init]; + [(MP42AudioTrack*)newTrack setChannels:mkvTrack->AV.Audio.Channels]; + [newTrack setAlternate_group:1]; + + for (MP42Track* audioTrack in _tracksArray) { + if ([audioTrack isMemberOfClass:[MP42AudioTrack class]]) + [newTrack setEnabled:NO]; + } + } + + // Text + else if (mkvTrack->Type == TT_SUB) { + newTrack = [[MP42SubtitleTrack alloc] init]; + [newTrack setAlternate_group:2]; + + for (MP42Track* subtitleTrack in _tracksArray) { + if ([subtitleTrack isMemberOfClass:[MP42SubtitleTrack class]]) + [newTrack setEnabled:NO]; + } + } + + if (newTrack) { + newTrack.format = [self matroskaCodecIDToHumanReadableName:mkvTrack]; + newTrack.Id = i; + newTrack.sourceURL = _fileURL; + newTrack.dataLength = trackSizes[i]; + if (mkvTrack->Type == TT_AUDIO) + newTrack.startOffset = [self matroskaTrackStartTime:mkvTrack Id:i]; + + if ([newTrack.format isEqualToString:MP42VideoFormatH264]) { + uint8_t* avcCAtom = (uint8_t *)malloc(mkvTrack->CodecPrivateSize); // mkv stores h.264 avcC in CodecPrivate + memcpy(avcCAtom, mkvTrack->CodecPrivate, mkvTrack->CodecPrivateSize); + if (mkvTrack->CodecPrivateSize >= 3) { + [(MP42VideoTrack*)newTrack setOrigProfile:avcCAtom[1]]; + [(MP42VideoTrack*)newTrack setNewProfile:avcCAtom[1]]; + [(MP42VideoTrack*)newTrack setOrigLevel:avcCAtom[3]]; + [(MP42VideoTrack*)newTrack setNewLevel:avcCAtom[3]]; + } + free(avcCAtom); + } + + double trackTimecodeScale = mkv_TruncFloat(mkvTrack->TimecodeScale); + SegmentInfo *segInfo = mkv_GetFileInfo(_matroskaFile); + UInt64 scaledDuration = (UInt64)segInfo->Duration / 1000000 * trackTimecodeScale; + + newTrack.duration = scaledDuration; + + if (scaledDuration > _fileDuration) + _fileDuration = scaledDuration; + + if ([self matroskaTrackName:mkvTrack]) + newTrack.name = [self matroskaTrackName:mkvTrack]; + iso639_lang_t *isoLanguage = lang_for_code2(mkvTrack->Language); + newTrack.language = [NSString stringWithUTF8String:isoLanguage->eng_name]; + + [_tracksArray addObject:newTrack]; + [newTrack release]; + } + } + + Chapter* chapters; + unsigned count; + mkv_GetChapters(_matroskaFile, &chapters, &count); + + if (count) { + MP42ChapterTrack *newTrack = [[MP42ChapterTrack alloc] init]; + + SegmentInfo *segInfo = mkv_GetFileInfo(_matroskaFile); + UInt64 scaledDuration = (UInt64)segInfo->Duration / 1000000; + [newTrack setDuration:scaledDuration]; + + if (count) { + unsigned int xi = 0; + for (xi = 0; xi < chapters->nChildren; xi++) { + uint64_t timestamp = (chapters->Children[xi].Start) / 1000000; + if (!xi) + timestamp = 0; + if (xi && timestamp == 0) + continue; + if (chapters->Children[xi].Display && strlen(chapters->Children[xi].Display->String)) + [newTrack addChapter:[NSString stringWithUTF8String:chapters->Children[xi].Display->String] + duration:timestamp]; + else + [newTrack addChapter:[NSString stringWithFormat:@"Chapter %d", xi+1] + duration:timestamp]; + } + } + [_tracksArray addObject:newTrack]; + [newTrack release]; + } + + if (trackSizes) + free(trackSizes); + + _metadata = [[self readMatroskaMetadata] retain]; + } + + return self; +} + +- (MP42Metadata *)readMatroskaMetadata +{ + MP42Metadata *mkvMetadata = [[MP42Metadata alloc] init]; + + SegmentInfo *segInfo = mkv_GetFileInfo(_matroskaFile); + if (segInfo->Title) + [mkvMetadata setTag:[NSString stringWithUTF8String:segInfo->Title] forKey:@"Name"]; + + Tag* tags; + unsigned count; + + mkv_GetTags(_matroskaFile, &tags, &count); + if (count) { + unsigned int xi = 0; + for (xi = 0; xi < tags->nSimpleTags; xi++) { + + if (!strcmp(tags->SimpleTags[xi].Name, "TITLE")) + [mkvMetadata setTag:[NSString stringWithUTF8String:tags->SimpleTags[xi].Value] forKey:@"Name"]; + + if (!strcmp(tags->SimpleTags[xi].Name, "DATE_RELEASED")) + [mkvMetadata setTag:[NSString stringWithUTF8String:tags->SimpleTags[xi].Value] forKey:@"Release Date"]; + + if (!strcmp(tags->SimpleTags[xi].Name, "COMMENT")) + [mkvMetadata setTag:[NSString stringWithUTF8String:tags->SimpleTags[xi].Value] forKey:@"Comments"]; + + if (!strcmp(tags->SimpleTags[xi].Name, "DIRECTOR")) + [mkvMetadata setTag:[NSString stringWithUTF8String:tags->SimpleTags[xi].Value] forKey:@"Director"]; + + if (!strcmp(tags->SimpleTags[xi].Name, "COPYRIGHT")) + [mkvMetadata setTag:[NSString stringWithUTF8String:tags->SimpleTags[xi].Value] forKey:@"Copyright"]; + + if (!strcmp(tags->SimpleTags[xi].Name, "ARTIST")) + [mkvMetadata setTag:[NSString stringWithUTF8String:tags->SimpleTags[xi].Value] forKey:@"Artist"]; + } + } + + if ([mkvMetadata.tagsDict count]) + return [mkvMetadata autorelease]; + else { + [mkvMetadata release]; + return nil; + } +} + +- (uint64_t *)copyGuessedTrackDataLength +{ + uint64_t *trackSizes = NULL; + uint64_t *trackTimestamp; + uint64_t StartTime, EndTime, FilePos; + uint32_t Track, FrameSize, FrameFlags; + int i = 0; + + SegmentInfo *segInfo = mkv_GetFileInfo(_matroskaFile); + NSInteger trackCount = mkv_GetNumTracks(_matroskaFile); + + if (trackCount) { + trackSizes = (uint64_t *) malloc(sizeof(uint64_t) * trackCount); + trackTimestamp = (uint64_t *) malloc(sizeof(uint64_t) * trackCount); + + for (i= 0; i < trackCount; i++) { + trackSizes[i] = 0; + trackTimestamp[i] = 0; + } + + StartTime = 0; + i = 0; + while (StartTime < (segInfo->Duration / 64)) { + if (!mkv_ReadFrame(_matroskaFile, 0, &Track, &StartTime, &EndTime, &FilePos, &FrameSize, &FrameFlags)) { + trackSizes[Track] += FrameSize; + trackTimestamp[Track] = StartTime; + i++; + } + else + break; + } + + for (i= 0; i < trackCount; i++) + if (trackTimestamp[i] > 0) + trackSizes[i] = trackSizes[i] * (segInfo->Duration / trackTimestamp[i]); + + free(trackTimestamp); + mkv_Seek(_matroskaFile, 0, 0); + } + + return trackSizes; +} + +- (NSString *)matroskaCodecIDToHumanReadableName:(TrackInfo *)track +{ + if (track->CodecID) { + if (!strcmp(track->CodecID, "V_MPEG4/ISO/AVC")) + return MP42VideoFormatH264; + else if (!strcmp(track->CodecID, "A_AAC") || + !strcmp(track->CodecID, "A_AAC/MPEG4/LC") || + !strcmp(track->CodecID, "A_AAC/MPEG2/LC")) + return MP42AudioFormatAAC; + else if (!strcmp(track->CodecID, "A_AC3")) + return MP42AudioFormatAC3; + else if (!strcmp(track->CodecID, "V_MPEG4/ISO/SP")) + return MP42VideoFormatMPEG4Visual; + else if (!strcmp(track->CodecID, "V_MPEG4/ISO/ASP")) + return MP42VideoFormatMPEG4Visual; + else if (!strcmp(track->CodecID, "V_MPEG2")) + return MP42VideoFormatMPEG2; + else if (!strcmp(track->CodecID, "A_DTS")) + return MP42AudioFormatDTS; + else if (!strcmp(track->CodecID, "A_VORBIS")) + return MP42AudioFormatVorbis; + else if (!strcmp(track->CodecID, "A_FLAC")) + return MP42AudioFormatFLAC; + else if (!strcmp(track->CodecID, "A_MPEG/L3")) + return MP42AudioFormatMP3; + else if (!strcmp(track->CodecID, "A_TRUEHD")) + return MP42AudioFormatTrueHD; + else if (!strcmp(track->CodecID, "A_MLP")) + return @"MLP"; + else if (!strcmp(track->CodecID, "S_TEXT/UTF8")) + return MP42SubtitleFormatText; + else if (!strcmp(track->CodecID, "S_TEXT/ASS") + || !strcmp(track->CodecID, "S_TEXT/SSA")) + return MP42SubtitleFormatSSA; + else if (!strcmp(track->CodecID, "S_VOBSUB")) + return MP42SubtitleFormatVobSub; + else if (!strcmp(track->CodecID, "S_HDMV/PGS")) + return MP42SubtitleFormatPGS; + + else + return [NSString stringWithUTF8String:track->CodecID]; + } + else { + return @"Unknown"; + } +} + +- (NSString *)matroskaTrackName:(TrackInfo *)track +{ + if(track->Name && strlen(track->Name)) + return [NSString stringWithUTF8String:track->Name]; + else + return nil; +} + +- (uint64_t)matroskaTrackStartTime:(TrackInfo *)track Id:(MP4TrackId)Id +{ + uint64_t StartTime, EndTime, FilePos; + uint32_t Track, FrameSize, FrameFlags; + + /* mask other tracks because we don't need them */ + unsigned int TrackMask = ~0; + TrackMask &= ~(1 << Id); + + mkv_SetTrackMask(_matroskaFile, TrackMask); + mkv_ReadFrame(_matroskaFile, 0, &Track, &StartTime, &EndTime, &FilePos, &FrameSize, &FrameFlags); + mkv_Seek(_matroskaFile, 0, 0); + + return StartTime / 1000000; +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + TrackInfo *trackInfo = mkv_GetTrackInfo(_matroskaFile, [track sourceId]); + if (trackInfo->Type == TT_VIDEO) + return 100000; + else if (trackInfo->Type == TT_AUDIO) { + NSUInteger sampleRate = mkv_TruncFloat(trackInfo->AV.Audio.SamplingFreq); + if (!strcmp(trackInfo->CodecID, "A_AC3")) { + if (sampleRate < 24000) + return 48000; + } + + return mkv_TruncFloat(trackInfo->AV.Audio.SamplingFreq); + } + + return 1000; +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + return NSMakeSize([(MP42VideoTrack*)track width], [(MP42VideoTrack*) track height]); +} + +- (NSData*)magicCookieForTrack:(MP42Track *)track +{ + if (!_matroskaFile) + return nil; + + TrackInfo *trackInfo = mkv_GetTrackInfo(_matroskaFile, [track sourceId]); + + if ((!strcmp(trackInfo->CodecID, "A_AAC/MPEG4/LC") || + !strcmp(trackInfo->CodecID, "A_AAC/MPEG2/LC")) && !trackInfo->CodecPrivateSize) { + NSMutableData *magicCookie = [[NSMutableData alloc] init]; + uint8_t aac[2]; + aac[0] = 0x11; + aac[1] = 0x90; + + [magicCookie appendBytes:aac length:2]; + return [magicCookie autorelease]; + } + + if (!strcmp(trackInfo->CodecID, "A_AC3")) { + mkv_SetTrackMask(_matroskaFile, ~(1 << [track sourceId])); + + uint64_t StartTime, EndTime, FilePos; + uint32_t rt, FrameSize, FrameFlags; + uint8_t *frame = NULL; + + // read first header to create track + int firstFrame = mkv_ReadFrame(_matroskaFile, 0, &rt, &StartTime, &EndTime, &FilePos, &FrameSize, &FrameFlags); + if (firstFrame != 0) + return nil; + + if (readMkvPacket(_ioStream, trackInfo, FilePos, &frame, &FrameSize)) { + // parse AC3 header + // collect all the necessary meta information + uint32_t fscod, frmsizecod, bsid, bsmod, acmod, lfeon; + uint32_t lfe_offset = 4; + + fscod = (*(frame+4) >> 6) & 0x3; + frmsizecod = (*(frame+4) & 0x3f) >> 1; + bsid = (*(frame+5) >> 3) & 0x1f; + bsmod = (*(frame+5) & 0xf); + acmod = (*(frame+6) >> 5) & 0x7; + if (acmod == 2) + lfe_offset -= 2; + else { + if ((acmod & 1) && acmod != 1) + lfe_offset -= 2; + if (acmod & 4) + lfe_offset -= 2; + } + lfeon = (*(frame+6) >> lfe_offset) & 0x1; + + mkv_Seek(_matroskaFile, 0, 0); + + NSMutableData *ac3Info = [[NSMutableData alloc] init]; + [ac3Info appendBytes:&fscod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsid length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&acmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&lfeon length:sizeof(uint64_t)]; + [ac3Info appendBytes:&frmsizecod length:sizeof(uint64_t)]; + + free(frame); + + return [ac3Info autorelease]; + } + else + return nil; + } + else if (!strcmp(trackInfo->CodecID, "S_VOBSUB")) { + char *string = (char *) trackInfo->CodecPrivate; + char *palette = strnstr(string, "palette:", trackInfo->CodecPrivateSize); + + UInt32 colorPalette[16]; + + if (palette != NULL) { + sscanf(palette, "palette: %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx", + &colorPalette[ 0], &colorPalette[ 1], &colorPalette[ 2], &colorPalette[ 3], + &colorPalette[ 4], &colorPalette[ 5], &colorPalette[ 6], &colorPalette[ 7], + &colorPalette[ 8], &colorPalette[ 9], &colorPalette[10], &colorPalette[11], + &colorPalette[12], &colorPalette[13], &colorPalette[14], &colorPalette[15]); + } + return [NSData dataWithBytes:colorPalette length:sizeof(UInt32)*16]; + } + + NSData * magicCookie = [NSData dataWithBytes:trackInfo->CodecPrivate length:trackInfo->CodecPrivateSize]; + + if (magicCookie) + return magicCookie; + else + return nil; +} + +// Methods to extract all the samples from the active tracks at the same time + +- (void)demux:(id)sender +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + uint64_t StartTime, EndTime, FilePos; + uint32_t Track, FrameSize, FrameFlags; + uint8_t *frame = NULL; + + MP42Track *track = nil; + MatroskaDemuxHelper *demuxHelper = nil; + MatroskaSample *frameSample = nil, * currentSample = nil; + int64_t offset, minOffset = 0, duration, next_duration; + + const unsigned int bufferSize = 20; + + /* mask other tracks because we don't need them */ + unsigned int TrackMask = ~0; + + for (MP42Track *track in _inputTracks) { + TrackMask &= ~(1 << [track sourceId]); + track.muxer_helper->demuxer_context = [[MatroskaDemuxHelper alloc] init]; + } + + mkv_SetTrackMask(_matroskaFile, TrackMask); + + while (!mkv_ReadFrame(_matroskaFile, 0, &Track, &StartTime, &EndTime, &FilePos, &FrameSize, &FrameFlags) && !_cancelled) { + _progress = (StartTime / _fileDuration / 10000); + muxer_helper *helper = NULL; + + for (MP42Track *fTrack in _inputTracks){ + if (fTrack.sourceId == Track) { + helper = fTrack.muxer_helper; + demuxHelper = helper->demuxer_context; + track = fTrack; + } + } + + TrackInfo *trackInfo = mkv_GetTrackInfo(_matroskaFile, Track); + + if (trackInfo->Type == TT_AUDIO) { + demuxHelper->samplesWritten++; + + if (readMkvPacket(_ioStream, trackInfo, FilePos, &frame, &FrameSize)) { + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = frame; + sample->size = FrameSize; + sample->duration = MP4_INVALID_DURATION; + sample->offset = 0; + sample->timestamp = StartTime; + sample->isSync = YES; + sample->trackId = track.sourceId; + + [self enqueue:sample]; + [sample release]; + } + } + + if (trackInfo->Type == TT_SUB) { + if (readMkvPacket(_ioStream, trackInfo, FilePos, &frame, &FrameSize)) { + if (strcmp(trackInfo->CodecID, "S_VOBSUB") && strcmp(trackInfo->CodecID, "S_HDMV/PGS")) { + if (!demuxHelper->ss) + demuxHelper->ss = [[SBSubSerializer alloc] init]; + + NSString *string = [[[NSString alloc] initWithBytes:frame length:FrameSize encoding:NSUTF8StringEncoding] autorelease]; + if (!strcmp(trackInfo->CodecID, "S_TEXT/ASS") || !strcmp(trackInfo->CodecID, "S_TEXT/SSA")) + string = StripSSALine(string); + + if ([string length]) { + SBSubLine *sl = [[SBSubLine alloc] initWithLine:string start:StartTime/1000000 end:EndTime/1000000]; + [demuxHelper->ss addLine:[sl autorelease]]; + } + demuxHelper->samplesWritten++; + free(frame); + } + else { + MP42SampleBuffer *nextSample = [[MP42SampleBuffer alloc] init]; + + nextSample->duration = 0; + nextSample->offset = 0; + nextSample->timestamp = StartTime; + nextSample->data = frame; + nextSample->size = FrameSize; + nextSample->isSync = YES; + nextSample->trackId = track.sourceId; + + // PGS are usually stored with just the start time, and blank samples to fill the gaps + if (!strcmp(trackInfo->CodecID, "S_HDMV/PGS")) { + if (!demuxHelper->previousSample) { + demuxHelper->previousSample = [[MP42SampleBuffer alloc] init]; + demuxHelper->previousSample->duration = StartTime / 1000000; + demuxHelper->previousSample->offset = 0; + demuxHelper->previousSample->timestamp = 0; + demuxHelper->previousSample->isSync = YES; + demuxHelper->previousSample->trackId = track.sourceId; + } + else { + if (nextSample->timestamp < demuxHelper->previousSample->timestamp) { + // Out of order samples? swap the next with the previous + MP42SampleBuffer *temp = nextSample; + nextSample = demuxHelper->previousSample; + demuxHelper->previousSample = temp; + } + + demuxHelper->previousSample->duration = (nextSample->timestamp - demuxHelper->previousSample->timestamp) / 1000000; + } + + [self enqueue:demuxHelper->previousSample]; + [demuxHelper->previousSample release]; + + demuxHelper->previousSample = nextSample; + demuxHelper->samplesWritten++; + } + // VobSub seems to have an end duration, and no blank samples, so create a new one each time to fill the gaps + else if (!strcmp(trackInfo->CodecID, "S_VOBSUB")) { + if (StartTime > demuxHelper->current_time) { + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->duration = (StartTime - demuxHelper->current_time) / 1000000; + sample->size = 2; + sample->data = calloc(1, 2); + sample->isSync = YES; + sample->trackId = track.sourceId; + + [self enqueue:sample]; + [sample release]; + } + + nextSample->duration = (EndTime - StartTime ) / 1000000; + + [self enqueue:nextSample]; + [nextSample release]; + + demuxHelper->current_time = EndTime; + } + } + } + } + + else if (trackInfo->Type == TT_VIDEO) { + + /* read frames from file */ + frameSample = [[MatroskaSample alloc] init]; + frameSample->startTime = StartTime; + frameSample->endTime = EndTime; + frameSample->filePos = FilePos; + frameSample->frameSize = FrameSize; + frameSample->frameFlags = FrameFlags; + [demuxHelper->queue addObject:frameSample]; + [frameSample release]; + + if ([demuxHelper->queue count] < bufferSize) + continue; + else { + currentSample = [demuxHelper->queue objectAtIndex:demuxHelper->buffer]; + + // matroska stores only the start and end time, so we need to recreate + // the frame duration and the offset from the start time, the end time is useless + // duration calculation + duration = ((MatroskaSample*)[demuxHelper->queue lastObject])->startTime - currentSample->startTime; + + for (MatroskaSample *sample in demuxHelper->queue) + if (sample != currentSample && (sample->startTime >= currentSample->startTime)) + if ((next_duration = (sample->startTime - currentSample->startTime)) < duration) + duration = next_duration; + + // offset calculation + offset = currentSample->startTime - demuxHelper->current_time; + // save the minimum offset, used later to keep all the offset values positive + if (offset < minOffset) + minOffset = offset; + + [demuxHelper->offsetsArray addObject:[NSNumber numberWithLongLong:offset]]; + + demuxHelper->current_time += duration; + + if (readMkvPacket(_ioStream, trackInfo, currentSample->filePos, &frame, ¤tSample->frameSize)) { + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = frame; + sample->size = currentSample->frameSize; + sample->duration = duration / 10000.0f; + sample->offset = offset / 10000.0f; + sample->timestamp = StartTime; + sample->isSync = currentSample->frameFlags & FRAME_KF; + sample->trackId = track.sourceId; + + demuxHelper->samplesWritten++; + + if (sample->offset < demuxHelper->minDisplayOffset) + demuxHelper->minDisplayOffset = sample->offset; + + if (demuxHelper->buffer >= bufferSize) + [demuxHelper->queue removeObjectAtIndex:0]; + if (demuxHelper->buffer < bufferSize) + demuxHelper->buffer++; + + [self enqueue:sample]; + [sample release]; + } + else + continue; + } + } + } + + for (MP42Track *track in _inputTracks) { + muxer_helper *helper = track.muxer_helper; + demuxHelper = helper->demuxer_context; + + if (demuxHelper->queue) { + TrackInfo *trackInfo = mkv_GetTrackInfo(_matroskaFile, [track sourceId]); + + while ([demuxHelper->queue count]) { + if (demuxHelper->bufferFlush == 1) { + // add a last sample to get the duration for the last frame + MatroskaSample *lastSample = [demuxHelper->queue lastObject]; + for (MatroskaSample *sample in demuxHelper->queue) { + if (sample->startTime > lastSample->startTime) + lastSample = sample; + } + frameSample = [[MatroskaSample alloc] init]; + frameSample->startTime = lastSample->endTime; + [demuxHelper->queue addObject:frameSample]; + [frameSample release]; + } + currentSample = [demuxHelper->queue objectAtIndex:demuxHelper->buffer]; + + // matroska stores only the start and end time, so we need to recreate + // the frame duration and the offset from the start time, the end time is useless + // duration calculation + duration = ((MatroskaSample*)[demuxHelper->queue lastObject])->startTime - currentSample->startTime; + + for (MatroskaSample *sample in demuxHelper->queue) + if (sample != currentSample && (sample->startTime >= currentSample->startTime)) + if ((next_duration = (sample->startTime - currentSample->startTime)) < duration) + duration = next_duration; + + // offset calculation + offset = currentSample->startTime - demuxHelper->current_time; + // save the minimum offset, used later to keep the all the offset values positive + if (offset < minOffset) + minOffset = offset; + + [demuxHelper->offsetsArray addObject:[NSNumber numberWithLongLong:offset]]; + + demuxHelper->current_time += duration; + + if (readMkvPacket(_ioStream, trackInfo, currentSample->filePos, &frame, ¤tSample->frameSize)) { + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = frame; + sample->size = currentSample->frameSize; + sample->duration = duration / 10000.0f; + sample->offset = offset / 10000.0f; + sample->timestamp = StartTime; + sample->isSync = currentSample->frameFlags & FRAME_KF; + sample->trackId = track.sourceId; + + demuxHelper->samplesWritten++; + + if (sample->offset < demuxHelper->minDisplayOffset) + demuxHelper->minDisplayOffset = sample->offset; + + if (demuxHelper->buffer >= bufferSize) + [demuxHelper->queue removeObjectAtIndex:0]; + + [self enqueue:sample]; + [sample release]; + + demuxHelper->bufferFlush++; + if (demuxHelper->bufferFlush >= bufferSize - 1) { + break; + } + } + else + continue; + } + } + + if (demuxHelper->ss) { + MP42SampleBuffer *sample = nil; + MP4TrackId dstTrackId = track.sourceId; + SBSubSerializer *ss = demuxHelper->ss; + + [ss setFinished:YES]; + + while (![ss isEmpty] && !_cancelled) { + SBSubLine *sl = [ss getSerializedPacket]; + + if ([sl->line isEqualToString:@"\n"]) + sample = copyEmptySubtitleSample(dstTrackId, sl->end_time - sl->begin_time, NO); + else + sample = copySubtitleSample(dstTrackId, sl->line, sl->end_time - sl->begin_time, NO, NO, CGSizeMake(0, 0), 0); + + if (!sample) + break; + + demuxHelper->current_time += sample->duration; + sample->timestamp = demuxHelper->current_time; + + [self enqueue:sample]; + [sample release]; + + demuxHelper->samplesWritten++; + } + } + } + + [self setDone:YES]; + [pool release]; +} + +- (void)startReading +{ + [super startReading]; + + if (!_matroskaFile) + return; + + if (!_demuxerThread && !_done) { + _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; + [_demuxerThread setName:@"Matroska Demuxer"]; + [_demuxerThread start]; + } +} + +- (BOOL)cleanUp:(MP4FileHandle)fileHandle +{ + for (MP42Track *track in _outputsTracks) { + MP42Track *inputTrack = [self inputTrackWithTrackID:track.sourceId]; + + MatroskaDemuxHelper *demuxHelper = inputTrack.muxer_helper->demuxer_context; + MP4TrackId trackId = track.Id; + + if (demuxHelper->minDisplayOffset != 0) { + int i; + for (i = 0; i < demuxHelper->samplesWritten; i++) + MP4SetSampleRenderingOffset(fileHandle, + trackId, + 1 + i, + MP4GetSampleRenderingOffset(fileHandle, trackId, 1+i) - demuxHelper->minDisplayOffset); + + MP4Duration editDuration = MP4ConvertFromTrackDuration(fileHandle, + trackId, + MP4GetTrackDuration(fileHandle, trackId), + MP4GetTimeScale(fileHandle)); + MP4AddTrackEdit(fileHandle, trackId, MP4_INVALID_EDIT_ID, - demuxHelper->minDisplayOffset, + editDuration, 0); + } + } + + return YES; +} + +- (void) dealloc +{ + /* close matroska parser */ + closeMatroskaFile(_matroskaFile, _ioStream); + + [super dealloc]; +} + +@end diff --git a/MP42/MP42Mp4Importer.h b/MP42/MP42Mp4Importer.h new file mode 100644 index 0000000..b983021 --- /dev/null +++ b/MP42/MP42Mp4Importer.h @@ -0,0 +1,18 @@ +// +// MP42MkvFileImporter.h +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import +#import "MP42FileImporter.h" +#import "MP42File.h" +#import "mp4v2.h" + +@interface MP42Mp4Importer : MP42FileImporter { + MP4FileHandle _fileHandle; +} + +@end \ No newline at end of file diff --git a/MP42/MP42Mp4Importer.m b/MP42/MP42Mp4Importer.m new file mode 100644 index 0000000..db64d2c --- /dev/null +++ b/MP42/MP42Mp4Importer.m @@ -0,0 +1,341 @@ +// +// MP42MkvFileImporter.m +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import "MP42Mp4Importer.h" +#import "SBLanguages.h" +#import "MP42Sample.h" + +@interface MP4DemuxkHelper : NSObject { +@public + MP4SampleId currentSampleId; + uint64_t totalSampleNumber; + MP4Timestamp currentTime; + uint64_t timeScale; + + uint32_t done; +} +@end + +@implementation MP4DemuxkHelper +@end + +@implementation MP42Mp4Importer + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError; +{ + if ((self = [super init])) { + _fileURL = [fileURL retain]; + + MP42File *sourceFile = [[MP42File alloc] initWithExistingFile:_fileURL andDelegate:self]; + + if(!sourceFile) { + if (outError) { + *outError = MP42Error(@"The movie could not be opened.", @"The file is not a mp4 file.", 100); + } + + [self release]; + return nil; + } + + _tracksArray = [[sourceFile tracks] mutableCopy]; + _metadata = [[sourceFile metadata] retain]; + + [sourceFile release]; + } + + return self; +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + return MP4GetTrackTimeScale(_fileHandle, [track sourceId]); +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + MP42VideoTrack* currentTrack = (MP42VideoTrack*) track; + + return NSMakeSize([currentTrack width], [currentTrack height]); +} + +- (NSData*)magicCookieForTrack:(MP42Track *)track +{ + if (!_fileHandle) + _fileHandle = MP4Read([[_fileURL path] UTF8String]); + + NSData *magicCookie = nil; + MP4TrackId srcTrackId = [track sourceId]; + + const char *trackType = MP4GetTrackType(_fileHandle, srcTrackId); + const char *media_data_name = MP4GetTrackMediaDataName(_fileHandle, srcTrackId); + + if (MP4_IS_AUDIO_TRACK_TYPE(trackType)) + { + if (!strcmp(media_data_name, "ac-3")) { + uint64_t fscod, bsid, bsmod, acmod, lfeon, bit_rate_code; + MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.ac-3.dac3.fscod", &fscod); + MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.ac-3.dac3.bsid", &bsid); + MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.ac-3.dac3.bsmod", &bsmod); + MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.ac-3.dac3.acmod", &acmod); + MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.ac-3.dac3.lfeon", &lfeon); + MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.ac-3.dac3.bit_rate_code", &bit_rate_code); + + NSMutableData *ac3Info = [[NSMutableData alloc] init]; + [ac3Info appendBytes:&fscod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsid length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&acmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&lfeon length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bit_rate_code length:sizeof(uint64_t)]; + + return [ac3Info autorelease]; + + } else if (!strcmp(media_data_name, "alac")) { + if (MP4HaveTrackAtom(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.alac.alac")) { + uint8_t* ppValue; + uint32_t pValueSize; + MP4GetTrackBytesProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.alac.alac.AppleLosslessMagicCookie", &ppValue, &pValueSize); + magicCookie = [NSData dataWithBytes:ppValue length:pValueSize]; + } + } + else { + uint8_t *ppConfig; uint32_t pConfigSize; + MP4GetTrackESConfiguration(_fileHandle, srcTrackId, &ppConfig, &pConfigSize); + magicCookie = [NSData dataWithBytes:ppConfig length:pConfigSize]; + free(ppConfig); + } + return magicCookie; + } + + else if (!strcmp(trackType, MP4_SUBPIC_TRACK_TYPE)) { + uint8_t *ppConfig; uint32_t pConfigSize; + MP4GetTrackESConfiguration(_fileHandle, srcTrackId, &ppConfig, &pConfigSize); + + UInt32* paletteG = (UInt32 *) ppConfig; + + int ii; + for ( ii = 0; ii < 16; ii++ ) + paletteG[ii] = yuv2rgb(EndianU32_BtoN(paletteG[ii])); + + magicCookie = [NSData dataWithBytes:paletteG length:pConfigSize]; + free(paletteG); + + return magicCookie; + } + + else if (MP4_IS_VIDEO_TRACK_TYPE(trackType)) + { + if (!strcmp(media_data_name, "avc1")) { + // Extract and rewrite some kind of avcC extradata from the mp4 file. + NSMutableData *avcCData = [[[NSMutableData alloc] init] autorelease]; + + uint8_t configurationVersion = 1; + uint8_t AVCProfileIndication; + uint8_t profile_compat; + uint8_t AVCLevelIndication; + uint32_t sampleLenFieldSizeMinusOne; + uint64_t temp; + + if (MP4GetTrackH264ProfileLevel(_fileHandle, srcTrackId, + &AVCProfileIndication, + &AVCLevelIndication) == false) { + return nil; + } + if (MP4GetTrackH264LengthSize(_fileHandle, srcTrackId, + &sampleLenFieldSizeMinusOne) == false) { + return nil; + } + sampleLenFieldSizeMinusOne--; + if (MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, + "mdia.minf.stbl.stsd.*[0].avcC.profile_compatibility", + &temp) == false) return nil; + profile_compat = temp & 0xff; + + [avcCData appendBytes:&configurationVersion length:sizeof(uint8_t)]; + [avcCData appendBytes:&AVCProfileIndication length:sizeof(uint8_t)]; + [avcCData appendBytes:&profile_compat length:sizeof(uint8_t)]; + [avcCData appendBytes:&AVCLevelIndication length:sizeof(uint8_t)]; + [avcCData appendBytes:&sampleLenFieldSizeMinusOne length:sizeof(uint8_t)]; + + uint8_t **seqheader, **pictheader; + uint32_t *pictheadersize, *seqheadersize; + uint32_t ix, iy; + MP4GetTrackH264SeqPictHeaders(_fileHandle, srcTrackId, + &seqheader, &seqheadersize, + &pictheader, &pictheadersize); + NSMutableData *seqData = [[NSMutableData alloc] init]; + for (ix = 0 , iy = 0; seqheadersize[ix] != 0; ix++) { + uint16_t temp = seqheadersize[ix] << 8; + [seqData appendBytes:&temp length:sizeof(uint16_t)]; + [seqData appendBytes:seqheader[ix] length:seqheadersize[ix]]; + iy++; + free(seqheader[ix]); + } + [avcCData appendBytes:&iy length:sizeof(uint8_t)]; + [avcCData appendData:seqData]; + + free(seqheader); + free(seqheadersize); + + NSMutableData *pictData = [[NSMutableData alloc] init]; + for (ix = 0, iy = 0; pictheadersize[ix] != 0; ix++) { + uint16_t temp = pictheadersize[ix] << 8; + [pictData appendBytes:&temp length:sizeof(uint16_t)]; + [pictData appendBytes:pictheader[ix] length:pictheadersize[ix]]; + iy++; + free(pictheader[ix]); + } + + [avcCData appendBytes:&iy length:sizeof(uint8_t)]; + [avcCData appendData:pictData]; + + free(pictheader); + free(pictheadersize); + + magicCookie = [avcCData copy]; + [seqData release]; + [pictData release]; + + return [magicCookie autorelease]; + } + } + + return nil; +} + +- (void)demux:(id)sender +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + NSInteger tracksNumber = [_inputTracks count]; + NSInteger tracksDone = 0; + MP4DemuxkHelper *demuxHelper; + + if (!_fileHandle) + return; + + for (MP42Track *track in _inputTracks) { + track.muxer_helper->demuxer_context = [[MP4DemuxkHelper alloc] init]; + demuxHelper = track.muxer_helper->demuxer_context; + demuxHelper->totalSampleNumber = MP4GetTrackNumberOfSamples(_fileHandle, track.sourceId); + demuxHelper->timeScale = MP4GetTrackTimeScale(_fileHandle, track.sourceId); + demuxHelper->done = 0; + } + + MP4Timestamp currentTime = 1; + MP4Duration duration = MP4GetDuration(_fileHandle); + MP4Duration timescale = MP4GetTimeScale(_fileHandle); + + while (tracksDone != tracksNumber) { + for (MP42Track *track in _inputTracks) { + muxer_helper *helper = track.muxer_helper; + demuxHelper = helper->demuxer_context; + + while (!_cancelled && demuxHelper->currentTime < demuxHelper->timeScale * currentTime && !demuxHelper->done) { + MP4TrackId srcTrackId = [track sourceId]; + uint8_t *pBytes = NULL; + uint32_t numBytes = 0; + MP4Duration duration; + MP4Duration renderingOffset; + MP4Timestamp pStartTime; + bool isSyncSample; + + demuxHelper->currentSampleId = demuxHelper->currentSampleId + 1; + + if (!MP4ReadSample(_fileHandle, + srcTrackId, + demuxHelper->currentSampleId, + &pBytes, &numBytes, + &pStartTime, &duration, &renderingOffset, + &isSyncSample)) { + demuxHelper->done++; + tracksDone++; + break; + } + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = pBytes; + sample->size = numBytes; + sample->duration = duration; + sample->offset = renderingOffset; + sample->timestamp = pStartTime; + sample->isSync = isSyncSample; + sample->trackId = track.sourceId; + + [self enqueue:sample]; + [sample release]; + + demuxHelper->currentTime = pStartTime; + } + } + + _progress = ((CGFloat)currentTime * timescale / duration) * 100; + currentTime += 3; + } + + [self setDone:YES]; + [pool release]; +} + +- (void)startReading +{ + if (!_fileHandle) + _fileHandle = MP4Read([[_fileURL path] UTF8String]); + + [super startReading]; + + if (!_demuxerThread && !_done) { + _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; + [_demuxerThread setName:@"MP4 Demuxer"]; + [_demuxerThread start]; + } +} + +- (BOOL)cleanUp:(MP4FileHandle)dstFileHandle +{ + for (MP42Track *track in _outputsTracks) { + MP4TrackId srcTrackId = track.sourceId; + MP4TrackId dstTrackId = track.Id; + + MP4Duration trackDuration = 0; + uint32_t i = 1, trackEditCount = MP4GetTrackNumberOfEdits(_fileHandle, srcTrackId); + while (i <= trackEditCount) { + MP4Timestamp editMediaStart = MP4GetTrackEditMediaStart(_fileHandle, srcTrackId, i); + MP4Duration editDuration = MP4ConvertFromMovieDuration(_fileHandle, + MP4GetTrackEditDuration(_fileHandle, srcTrackId, i), + MP4GetTimeScale(dstFileHandle)); + trackDuration += editDuration; + int8_t editDwell = MP4GetTrackEditDwell(_fileHandle, srcTrackId, i); + + MP4AddTrackEdit(dstFileHandle, dstTrackId, i, editMediaStart, editDuration, editDwell); + i++; + } + if (trackEditCount) + MP4SetTrackIntegerProperty(dstFileHandle, dstTrackId, "tkhd.duration", trackDuration); + else if (MP4GetSampleRenderingOffset(dstFileHandle, dstTrackId, 1)) { + uint32_t firstFrameOffset = MP4GetSampleRenderingOffset(dstFileHandle, dstTrackId, 1); + MP4Duration editDuration = MP4ConvertFromTrackDuration(_fileHandle, + srcTrackId, + MP4GetTrackDuration(_fileHandle, srcTrackId), + MP4GetTimeScale(dstFileHandle)); + MP4AddTrackEdit(dstFileHandle, dstTrackId, MP4_INVALID_EDIT_ID, firstFrameOffset, + editDuration, 0); + } + } + + return YES; +} + +- (void)dealloc +{ + if (_fileHandle) + MP4Close(_fileHandle, 0); + + [super dealloc]; +} + +@end diff --git a/MP42/MP42Muxer.h b/MP42/MP42Muxer.h new file mode 100644 index 0000000..00ed20f --- /dev/null +++ b/MP42/MP42Muxer.h @@ -0,0 +1,34 @@ +// +// MP42Muxer.h +// Subler +// +// Created by Damiano Galassi on 30/06/10. +// Copyright 2010 Damiano Galassi. All rights reserved. +// + +#import +#import "mp4v2.h" + +@class MP42Track; + +@protocol MP42MuxerDelegate +- (void)progressStatus:(CGFloat)progress; +@end + +@interface MP42Muxer : NSObject { + MP4FileHandle _fileHandle; + id _delegate; + + NSMutableArray *_workingTracks; + int32_t _cancelled; +} + +- (instancetype)initWithDelegate:(id )del; + +- (void)addTrack:(MP42Track *)track; + +- (BOOL)setup:(MP4FileHandle)fileHandle error:(NSError **)outError; +- (void)work; +- (void)cancel; + +@end diff --git a/MP42/MP42Muxer.m b/MP42/MP42Muxer.m new file mode 100644 index 0000000..20a951f --- /dev/null +++ b/MP42/MP42Muxer.m @@ -0,0 +1,450 @@ +// +// MP42Muxer.m +// Subler +// +// Created by Damiano Galassi on 30/06/10. +// Copyright 2010 Damiano Galassi. All rights reserved. +// + +#import "MP42Muxer.h" +#import "MP42File.h" +#import "MP42FileImporter.h" +#import "MP42Sample.h" +#import "MP42AudioConverter.h" +#import "MP42BitmapSubConverter.h" + +@implementation MP42Muxer + +- (instancetype)init +{ + if ((self = [super init])) { + _workingTracks = [[NSMutableArray alloc] init]; + } + return self; +} + +- (instancetype)initWithDelegate:(id )del +{ + if ((self = [super init])) { + _workingTracks = [[NSMutableArray alloc] init]; + _delegate = del; + } + + return self; +} + +- (void)addTrack:(MP42Track*)track +{ + if (![track isMemberOfClass:[MP42ChapterTrack class]]) + [_workingTracks addObject:track]; +} + +- (BOOL)setup:(MP4FileHandle)fileHandle error:(NSError **)outError +{ + BOOL noErr = YES; + _fileHandle = fileHandle; + + for (MP42Track *track in _workingTracks) { + MP4TrackId dstTrackId = 0; + NSData *magicCookie; + NSInteger timeScale; + muxer_helper *helper = track.muxer_helper; + + if (helper) { + magicCookie = [helper->importer magicCookieForTrack:track]; + timeScale = [helper->importer timescaleForTrack:track]; + } + else + continue; + + if([track isMemberOfClass:[MP42AudioTrack class]] && track.needConversion) { + MP42AudioConverter *audioConverter = [[MP42AudioConverter alloc] initWithTrack:(MP42AudioTrack *)track + andMixdownType:[(MP42AudioTrack *)track mixdownType] + error:outError]; + + if (audioConverter == nil) + noErr = NO; + + helper->converter = audioConverter; + } + if([track isMemberOfClass:[MP42SubtitleTrack class]] && ([track.sourceFormat isEqualToString:MP42SubtitleFormatVobSub] || [track.sourceFormat isEqualToString:MP42SubtitleFormatPGS]) && track.needConversion) { + MP42BitmapSubConverter *subConverter = [[MP42BitmapSubConverter alloc] initWithTrack:(MP42SubtitleTrack *)track + error:outError]; + + if (subConverter == nil) + noErr = NO; + + helper->converter = subConverter; + } + else if([track isMemberOfClass:[MP42SubtitleTrack class]] && track.needConversion) + track.format = MP42SubtitleFormatTx3g; + + // H.264 video track + if ([track isMemberOfClass:[MP42VideoTrack class]] && [track.format isEqualToString:MP42VideoFormatH264]) { + if ([magicCookie length] < sizeof(uint8_t) * 6) + continue; + + NSSize size = [helper->importer sizeForTrack:track]; + + uint8_t *avcCAtom = (uint8_t*)[magicCookie bytes]; + dstTrackId = MP4AddH264VideoTrack(fileHandle, timeScale, + MP4_INVALID_DURATION, + size.width, size.height, + avcCAtom[1], // AVCProfileIndication + avcCAtom[2], // profile_compat + avcCAtom[3], // AVCLevelIndication + avcCAtom[4]); // lengthSizeMinusOne + + SInt64 i; + int8_t spsCount = (avcCAtom[5] & 0x1f); + uint8_t ptrPos = 6; + for (i = 0; i < spsCount; i++) { + uint16_t spsSize = (avcCAtom[ptrPos++] << 8) & 0xff00; + spsSize += avcCAtom[ptrPos++] & 0xff; + MP4AddH264SequenceParameterSet(fileHandle, dstTrackId, + avcCAtom+ptrPos, spsSize); + ptrPos += spsSize; + } + + int8_t ppsCount = avcCAtom[ptrPos++]; + for (i = 0; i < ppsCount; i++) { + uint16_t ppsSize = (avcCAtom[ptrPos++] << 8) & 0xff00; + ppsSize += avcCAtom[ptrPos++] & 0xff; + MP4AddH264PictureParameterSet(fileHandle, dstTrackId, + avcCAtom+ptrPos, ppsSize); + ptrPos += ppsSize; + } + + MP4SetVideoProfileLevel(fileHandle, 0x15); + + [helper->importer setActiveTrack:track]; + } + + // MPEG-4 Visual video track + else if ([track isMemberOfClass:[MP42VideoTrack class]] && [track.format isEqualToString:MP42VideoFormatMPEG4Visual]) { + MP4SetVideoProfileLevel(fileHandle, MPEG4_SP_L3); + // Add video track + dstTrackId = MP4AddVideoTrack(fileHandle, timeScale, + MP4_INVALID_DURATION, + [(MP42VideoTrack*)track width], [(MP42VideoTrack*)track height], + MP4_MPEG4_VIDEO_TYPE); + + if ([magicCookie length]) + MP4SetTrackESConfiguration(fileHandle, dstTrackId, + [magicCookie bytes], + [magicCookie length]); + + [helper->importer setActiveTrack:track]; + } + + // Photo-JPEG video track + else if ([track isMemberOfClass:[MP42VideoTrack class]] && [track.format isEqualToString:MP42VideoFormatJPEG]) { + // Add video track + dstTrackId = MP4AddJpegVideoTrack(fileHandle, timeScale, + MP4_INVALID_DURATION, [(MP42VideoTrack*)track width], [(MP42VideoTrack*)track height]); + + [helper->importer setActiveTrack:track]; + } + + // AAC audio track + else if ([track isMemberOfClass:[MP42AudioTrack class]] && [track.format isEqualToString:MP42AudioFormatAAC]) { + dstTrackId = MP4AddAudioTrack(fileHandle, + timeScale, + 1024, MP4_MPEG4_AUDIO_TYPE); + + if (!track.needConversion && [magicCookie length]) { + MP4SetTrackESConfiguration(fileHandle, dstTrackId, + [magicCookie bytes], + [magicCookie length]); + } + + [helper->importer setActiveTrack:track]; + } + + // AC-3 audio track + else if ([track isMemberOfClass:[MP42AudioTrack class]] && [track.format isEqualToString:MP42AudioFormatAC3]) { + if ([magicCookie length] < sizeof(uint64_t) * 6) + continue; + + const uint64_t * ac3Info = (const uint64_t *)[magicCookie bytes]; + + dstTrackId = MP4AddAC3AudioTrack(fileHandle, + timeScale, + ac3Info[0], + ac3Info[1], + ac3Info[2], + ac3Info[3], + ac3Info[4], + ac3Info[5]); + + [helper->importer setActiveTrack:track]; + } + + // ALAC audio track + else if ([track isMemberOfClass:[MP42AudioTrack class]] && [track.format isEqualToString:MP42AudioFormatALAC]) { + dstTrackId = MP4AddALACAudioTrack(fileHandle, + timeScale); + if ([magicCookie length]) + MP4SetTrackBytesProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.alac.alac.AppleLosslessMagicCookie", [magicCookie bytes], [magicCookie length]); + + [helper->importer setActiveTrack:track]; + } + + // DTS audio track + else if ([track isMemberOfClass:[MP42AudioTrack class]] && [track.format isEqualToString:MP42AudioFormatDTS]) { + dstTrackId = MP4AddAudioTrack(fileHandle, + timeScale, + 512, 0xA9); + + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.*.channels", [(MP42AudioTrack*)track channels]); + [helper->importer setActiveTrack:track]; + } + + // 3GPP text track + else if ([track isMemberOfClass:[MP42SubtitleTrack class]] && [track.format isEqualToString:MP42SubtitleFormatTx3g]) { + NSSize subSize = NSMakeSize(0, 0); + NSSize videoSize = NSMakeSize(0, 0); + + NSInteger vPlacement = [(MP42SubtitleTrack*)track verticalPlacement]; + + for (id track in _workingTracks) + if ([track isMemberOfClass:[MP42VideoTrack class]]) { + videoSize.width = [track trackWidth]; + videoSize.height = [track trackHeight]; + break; + } + + if (!videoSize.width) { + MP4TrackId videoTrack = findFirstVideoTrack(fileHandle); + if (videoTrack) { + videoSize.width = getFixedVideoWidth(fileHandle, videoTrack); + videoSize.height = MP4GetTrackVideoHeight(fileHandle, videoTrack); + } + else { + videoSize.width = 640; + videoSize.height = 480; + } + } + if (!vPlacement) { + if ([(MP42SubtitleTrack*)track trackHeight]) + subSize.height = [(MP42SubtitleTrack*)track trackHeight]; + else + subSize.height = 0.15 * videoSize.height; + } + else + subSize.height = videoSize.height; + + const uint8_t textColor[4] = { 255,255,255,255 }; + dstTrackId = MP4AddSubtitleTrack(fileHandle, timeScale, videoSize.width, subSize.height); + + MP4SetTrackDurationPerChunk(fileHandle, dstTrackId, timeScale / 8); + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "tkhd.alternate_group", 2); + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "tkhd.layer", -1); + + int32_t displayFlags = 0; + if (vPlacement) + displayFlags = 0x20000000; + if ([(MP42SubtitleTrack *)track someSamplesAreForced]) + displayFlags += 0x40000000; + else if ([(MP42SubtitleTrack *)track allSamplesAreForced]) + displayFlags += 0xC0000000; + + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.displayFlags", displayFlags); + + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.horizontalJustification", 1); + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.verticalJustification", -1); + + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.bgColorRed", 0); + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.bgColorGreen", 0); + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.bgColorBlue", 0); + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.bgColorAlpha", 0); + + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.defTextBoxBottom", subSize.height); + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.defTextBoxRight", videoSize.width); + + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.fontSize", videoSize.height * 0.05); + + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorRed", textColor[0]); + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorGreen", textColor[1]); + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorBlue", textColor[2]); + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorAlpha", textColor[3]); + + /* translate the track */ + if (!vPlacement) { + uint8_t* val; + uint8_t nval[36]; + uint32_t *ptr32 = (uint32_t*) nval; + uint32_t size; + + MP4GetTrackBytesProperty(fileHandle, dstTrackId, "tkhd.matrix", &val, &size); + memcpy(nval, val, size); + ptr32[7] = CFSwapInt32HostToBig( (videoSize.height * 0.85) * 0x10000); + + MP4SetTrackBytesProperty(fileHandle, dstTrackId, "tkhd.matrix", nval, size); + free(val); + } + + [(MP42SubtitleTrack*)track setTrackWidth:videoSize.width]; + [(MP42SubtitleTrack*)track setTrackHeight:subSize.height]; + + [helper->importer setActiveTrack:track]; + } + // VobSub bitmap track + else if ([track isMemberOfClass:[MP42SubtitleTrack class]] && [track.format isEqualToString:MP42SubtitleFormatVobSub]) { + if ([magicCookie length] < sizeof(uint32_t) * 16) + continue; + + dstTrackId = MP4AddSubpicTrack(fileHandle, timeScale, 640, 480); + + uint32_t *subPalette = (uint32_t*) [magicCookie bytes]; + int ii; + for ( ii = 0; ii < 16; ii++ ) + subPalette[ii] = rgb2yuv(subPalette[ii]); + + uint8_t palette[16][4]; + for ( ii = 0; ii < 16; ii++ ) { + palette[ii][0] = 0; + palette[ii][1] = (subPalette[ii] >> 16) & 0xff; + palette[ii][2] = (subPalette[ii] >> 8) & 0xff; + palette[ii][3] = (subPalette[ii]) & 0xff; + } + MP4SetTrackESConfiguration( fileHandle, dstTrackId, + (uint8_t*)palette, 16 * 4 ); + + [helper->importer setActiveTrack:track]; + } + + // Closed Caption text track + else if ([track isMemberOfClass:[MP42ClosedCaptionTrack class]]) { + NSSize videoSize = [helper->importer sizeForTrack:track]; + + for (id track in _workingTracks) + if ([track isMemberOfClass:[MP42VideoTrack class]]) { + videoSize.width = [track trackWidth]; + videoSize.height = [track trackHeight]; + break; + } + + if (!videoSize.width) { + MP4TrackId videoTrack = findFirstVideoTrack(fileHandle); + if (videoTrack) { + videoSize.width = getFixedVideoWidth(fileHandle, videoTrack); + videoSize.height = MP4GetTrackVideoHeight(fileHandle, videoTrack); + } + else { + videoSize.width = 640; + videoSize.height = 480; + } + } + + dstTrackId = MP4AddCCTrack(fileHandle, timeScale, videoSize.width, videoSize.height); + + [helper->importer setActiveTrack:track]; + } + else { + continue; + } + + MP4SetTrackDurationPerChunk(fileHandle, dstTrackId, timeScale / 8); + track.Id = dstTrackId; + } + + return noErr; +} + +- (void)work +{ + if (![_workingTracks count]) + return; + + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSMutableArray *trackImportersArray = [[NSMutableArray alloc] init]; + NSUInteger done = 0, update = 0; + CGFloat progress = 0; + + for (MP42Track *track in _workingTracks) { + if (![trackImportersArray containsObject:track.muxer_helper->importer]) + [trackImportersArray addObject:track.muxer_helper->importer]; + } + + for (id importerHelper in trackImportersArray) + [importerHelper startReading]; + + NSUInteger tracksImportersCount = [trackImportersArray count]; + NSUInteger tracksCount = [_workingTracks count]; + + for (;;) { + usleep(1000); + + // Iterate the tracks array and mux the samples + for (MP42Track *track in _workingTracks) { + MP42SampleBuffer *sampleBuffer = nil; + + for (int i = 0; i < 100 && (sampleBuffer = [track copyNextSample]) != nil; i++) { + if (!MP4WriteSample(_fileHandle, track.Id, + sampleBuffer->data, sampleBuffer->size, + sampleBuffer->duration, sampleBuffer->offset, + sampleBuffer->isSync)) + _cancelled = YES; + + [sampleBuffer release]; + } + done += (track.muxer_helper->done ? 1 : 0); + } + + if (_cancelled) + break; + + // If all tracks are done, exit the loop + if (done == tracksCount) + break; + else + done = 0; + + // Update progress + if (!(update % 200)) { + progress = 0; + for (id importerHelper in trackImportersArray) + progress += [importerHelper progress]; + + progress = progress /= tracksImportersCount; + + [_delegate progressStatus:progress]; + } + update++; + } + + // Write the converted audio track magic cookie + for (MP42Track *track in _workingTracks) { + if(track.muxer_helper->converter && track.needConversion && [track isMemberOfClass:[MP42AudioTrack class]]) { + NSData *magicCookie = [track.muxer_helper->converter magicCookie]; + MP4SetTrackESConfiguration(_fileHandle, track.Id, + [magicCookie bytes], + [magicCookie length]); + } + } + + // Stop the importers and clean ups + for (id importerHelper in trackImportersArray) { + if (_cancelled) + [importerHelper cancelReading]; + else + [importerHelper cleanUp:_fileHandle]; + } + + [trackImportersArray release]; + [pool release]; +} + +- (void)cancel +{ + OSAtomicIncrement32(&_cancelled); +} + +- (void)dealloc +{ + [_workingTracks release]; + [super dealloc]; +} + +@end diff --git a/MP42/MP42OCRWrapper.h b/MP42/MP42OCRWrapper.h new file mode 100644 index 0000000..266d0c1 --- /dev/null +++ b/MP42/MP42OCRWrapper.h @@ -0,0 +1,20 @@ +// +// SBOcr.h +// Subler +// +// Created by Damiano Galassi on 27/03/11. +// Copyright 2011 Damiano Galassi. All rights reserved. +// + +#import + +@interface MP42OCRWrapper : NSObject { + void *tess_base; + + NSString *_language; +} + +- (instancetype)initWithLanguage:(NSString *)language; +- (NSString *)performOCROnCGImage:(CGImageRef)image; + +@end diff --git a/MP42/MP42OCRWrapper.mm b/MP42/MP42OCRWrapper.mm new file mode 100644 index 0000000..14e0327 --- /dev/null +++ b/MP42/MP42OCRWrapper.mm @@ -0,0 +1,159 @@ +// +// SBOcr.mm +// Subler +// +// Created by Damiano Galassi on 27/03/11. +// Copyright 2011 Damiano Galassi. All rights reserved. +// + +#import "MP42OCRWrapper.h" +#import "SBLanguages.h" + +// Tesseract OCR +#include "baseapi.h" + +using namespace tesseract; + +class OCRWrapper { +public: +OCRWrapper(const char* lang, const char* base_path) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSString *path = nil; + if (base_path) + path = [[NSString stringWithUTF8String:base_path] stringByAppendingString:@"/"]; + else + path = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/Contents/Resources/"]; + + setenv("TESSDATA_PREFIX", [path UTF8String], 1); + + path = [path stringByAppendingString:@"tessdata/"]; + + tess_base_api.Init([path UTF8String], lang, OEM_DEFAULT); + + [pool release]; +} +char* OCRFrame(const unsigned char *image, size_t bytes_per_pixel, size_t bytes_per_line, size_t width, size_t height) { + char* text = tess_base_api.TesseractRect(image, + (int)bytes_per_pixel, + (int)bytes_per_line, + 0, 0, + (int)width, (int)height); + return text; +} + +void End() { + tess_base_api.End(); +} + +protected: + TessBaseAPI tess_base_api; +}; + +@implementation MP42OCRWrapper + +- (NSURL*) appSupportUrl +{ + NSURL *URL = nil; + + NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, + NSUserDomainMask, + YES); + if ([allPaths count]) { + NSString* path = [[allPaths lastObject] stringByAppendingPathComponent:@"Subler"]; + URL = [NSURL fileURLWithPath:path]; + + if (URL) { + return URL; + } + } + + return nil; + +} + +- (BOOL)tessdataAvailableForLanguage:(NSString*) language +{ + NSURL *URL = [self appSupportUrl]; + + if (URL) { + NSString* path = [[[URL path] stringByAppendingPathComponent:@"tessdata"] stringByAppendingFormat:@"/%@.traineddata", language]; + URL = [NSURL fileURLWithPath:path]; + + if ([[NSFileManager defaultManager] fileExistsAtPath:[URL path]]) { + return YES; + } + } + + return NO; +} + + +- (instancetype)init +{ + if ((self = [super init])) + { + tess_base = (void *)new OCRWrapper(lang_for_english([_language UTF8String])->iso639_2, NULL); + } + return self; +} + +- (instancetype)initWithLanguage:(NSString *)language +{ + if ((self = [super init])) + { + _language = [language retain]; + + NSString * lang = [NSString stringWithUTF8String:lang_for_english([_language UTF8String])->iso639_2]; + NSURL *dataURL = [self appSupportUrl]; + if (![self tessdataAvailableForLanguage:lang]) { + lang = @"eng"; + dataURL = nil; + } + + tess_base = (void *)new OCRWrapper([lang UTF8String], [[dataURL path] UTF8String]); + } + return self; +} + +- (NSString *)performOCROnCGImage:(CGImageRef)cgImage { + NSMutableString * text; + + OCRWrapper *ocr = (OCRWrapper *)tess_base; + size_t bytes_per_line = CGImageGetBytesPerRow(cgImage); + size_t bytes_per_pixel = CGImageGetBitsPerPixel(cgImage) / 8.0; + size_t width = CGImageGetWidth(cgImage); + size_t height = CGImageGetHeight(cgImage); + + CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(cgImage)); + const UInt8 *imageData = CFDataGetBytePtr(data); + + char* string = ocr->OCRFrame(imageData, + bytes_per_pixel, + bytes_per_line, + width, + height); + CFRelease(data); + + if (string && strlen(string)) { + text = [NSMutableString stringWithUTF8String:string]; + if ([text characterAtIndex:[text length] -1] == '\n') + [text replaceOccurrencesOfString:@"\n\n" withString:@"" options:nil range:NSMakeRange(0,[text length])]; + } + else + text = nil; + + delete[]string; + + return text; + +} + +- (void)dealloc { + OCRWrapper *ocr = (OCRWrapper *)tess_base; + ocr->End(); + delete ocr; + + [_language release]; + [super dealloc]; +} +@end diff --git a/MP42/MP42QTImporter.h b/MP42/MP42QTImporter.h new file mode 100644 index 0000000..e69c2f0 --- /dev/null +++ b/MP42/MP42QTImporter.h @@ -0,0 +1,20 @@ +// +// MP42MkvFileImporter.h +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#if !__LP64__ +#import +#import "MP42FileImporter.h" +#import + +@interface MP42QTImporter : MP42FileImporter { + QTMovie *_sourceFile; +} + +@end + +#endif \ No newline at end of file diff --git a/MP42/MP42QTImporter.m b/MP42/MP42QTImporter.m new file mode 100644 index 0000000..cb297f4 --- /dev/null +++ b/MP42/MP42QTImporter.m @@ -0,0 +1,1002 @@ +// +// MP42MkvFileImporter.m +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#if !__LP64__ +#import "MP42QTImporter.h" +#import "MP42File.h" +#import "MP42Image.h" +#import +#import +#import "SBLanguages.h" +#import "QTKitDecrap.h" +#include "avcodec.h" + +@interface MP42QTImporter(Private) + -(void) movieLoaded; + -(NSString*)formatForTrack: (QTTrack *)track; + -(NSString*)langForTrack: (QTTrack *)track; +@end + +@interface MovDemuxHelper : NSObject { +@public + MP4SampleId currentSampleId; + uint64_t totalSampleNumber; + int64_t minDisplayOffset; + MP4Timestamp currentTime; +} +@end + +@implementation MovDemuxHelper +@end + +@implementation MP42QTImporter + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError +{ + if ((self = [super init])) { + _fileURL = [fileURL retain]; + + NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys: + _fileURL, QTMovieURLAttribute, + @NO, @"QTMovieOpenAsyncRequiredAttribute", + @NO, @"QTMovieOpenAsyncOKAttribute", + nil]; + + if (dispatch_get_current_queue() != dispatch_get_main_queue()) { + dispatch_sync(dispatch_get_main_queue(), ^{ + _sourceFile = [[QTMovie alloc] initWithAttributes:dict + error:outError]; + }); + } + else + _sourceFile = [[QTMovie alloc] initWithAttributes:dict + error:outError]; + + if (_sourceFile) + [self movieLoaded]; + else { + [self release]; + + return nil; + } + } + + return self; +} + +-(void) movieLoaded +{ + for (QTTrack *track in [_sourceFile tracks]) + if ([[track attributeForKey:QTTrackIsChapterTrackAttribute] boolValue]) + _chapterId = [[track attributeForKey:QTTrackIDAttribute] integerValue]; + + _tracksArray = [[NSMutableArray alloc] init]; + + if (NSClassFromString(@"QTMetadataItem")) //QTMetadataItem is only 10.7+ + [self convertMetadata]; + + for (QTTrack *track in [_sourceFile tracks]) { + NSString* mediaType = [track attributeForKey:QTTrackMediaTypeAttribute]; + MP42Track *newTrack = nil; + + Track qtcTrack = [track quickTimeTrack]; + Media media = GetTrackMedia(qtcTrack); + + // Video + if ([mediaType isEqualToString:QTMediaTypeVideo]) { + if ([[self formatForTrack:track] isEqualToString:MP42SubtitleFormatText]) { + newTrack = [[MP42SubtitleTrack alloc] init]; + [(MP42SubtitleTrack*)newTrack setTrackWidth:80]; + } + else { + newTrack = [[MP42VideoTrack alloc] init]; + + NSSize dimension = [track apertureModeDimensionsForMode:QTMovieApertureModeClean]; + [(MP42VideoTrack*)newTrack setTrackWidth: dimension.width]; + [(MP42VideoTrack*)newTrack setTrackHeight: dimension.height]; + + long pcount, ccount; + // Get the sample description + SampleDescriptionHandle desc = (SampleDescriptionHandle) NewHandle(0); + GetMediaSampleDescription(media, 1, desc); + ImageDescriptionHandle imgDesc = (ImageDescriptionHandle) desc; + + // Get dimensions of track media and define video dimensions accordingly. + [(MP42VideoTrack*)newTrack setWidth: (**imgDesc).width]; + [(MP42VideoTrack*)newTrack setHeight: (**imgDesc).height]; + + // Read pixel aspect ratio and clean aperture + CountImageDescriptionExtensionType(imgDesc, kPixelAspectRatioImageDescriptionExtension, &pcount); + CountImageDescriptionExtensionType(imgDesc, kCleanApertureImageDescriptionExtension, &ccount); + if (pcount > 0) { + Handle pasp = NewHandle(0); + GetImageDescriptionExtension(imgDesc, &pasp, kPixelAspectRatioImageDescriptionExtension, 1); + + [(MP42VideoTrack*)newTrack setHSpacing:CFSwapInt32BigToHost(((PixelAspectRatioImageDescriptionExtension*)(*pasp))->hSpacing)]; + [(MP42VideoTrack*)newTrack setVSpacing: CFSwapInt32BigToHost(((PixelAspectRatioImageDescriptionExtension*)(*pasp))->vSpacing)]; + + DisposeHandle(pasp); + } + if (ccount > 0) { + Handle clap = NewHandle(0); + GetImageDescriptionExtension(imgDesc, &clap, kCleanApertureImageDescriptionExtension, 1); + + [(MP42VideoTrack*)newTrack setCleanApertureWidthN:CFSwapInt32BigToHost(((CleanApertureImageDescriptionExtension*)(*clap))->cleanApertureWidthN)]; + [(MP42VideoTrack*)newTrack setCleanApertureWidthD: CFSwapInt32BigToHost(((CleanApertureImageDescriptionExtension*)(*clap))->cleanApertureWidthD)]; + [(MP42VideoTrack*)newTrack setCleanApertureHeightN: CFSwapInt32BigToHost(((CleanApertureImageDescriptionExtension*)(*clap))->cleanApertureHeightN)]; + [(MP42VideoTrack*)newTrack setCleanApertureHeightD: CFSwapInt32BigToHost(((CleanApertureImageDescriptionExtension*)(*clap))->cleanApertureHeightD)]; + [(MP42VideoTrack*)newTrack setHorizOffN: CFSwapInt32BigToHost(((CleanApertureImageDescriptionExtension*)(*clap))->horizOffN)]; + [(MP42VideoTrack*)newTrack setHorizOffD: CFSwapInt32BigToHost(((CleanApertureImageDescriptionExtension*)(*clap))->horizOffD)]; + [(MP42VideoTrack*)newTrack setVertOffN: CFSwapInt32BigToHost(((CleanApertureImageDescriptionExtension*)(*clap))->vertOffN)]; + [(MP42VideoTrack*)newTrack setVertOffD: CFSwapInt32BigToHost(((CleanApertureImageDescriptionExtension*)(*clap))->vertOffD)]; + + DisposeHandle(clap); + } + + // Hack to setup PASP if none exists + if (!pcount && !ccount && dimension.width != (**imgDesc).width) { + AVRational dar, sar, invPixelSize; + dar = (AVRational){dimension.width, dimension.height}; + invPixelSize = (AVRational){(**imgDesc).width, (**imgDesc).height}; + sar = av_mul_q(dar, invPixelSize); + + av_reduce(&sar.num, &sar.den, sar.num, sar.den, fixed1); + + [(MP42VideoTrack*)newTrack setHSpacing:sar.num]; + [(MP42VideoTrack*)newTrack setVSpacing:sar.den]; + } + } + } + + // Audio + else if ([mediaType isEqualToString:QTMediaTypeSound]) { + newTrack = [[MP42AudioTrack alloc] init]; + + OSStatus err = noErr; + + // Get the sample description + SampleDescriptionHandle desc = (SampleDescriptionHandle) NewHandle(0); + GetMediaSampleDescription(media, 1, desc); + + ByteCount channelLayoutSize; + AudioChannelLayout *channelLayout = NULL; + + SoundDescriptionHandle sndDesc = (SoundDescriptionHandle) desc; + + err = QTSoundDescriptionGetPropertyInfo(sndDesc, kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_AudioChannelLayout, + NULL, &channelLayoutSize, NULL); + require_noerr(err, bail); + + channelLayout = (AudioChannelLayout*)malloc(channelLayoutSize); + + err = QTSoundDescriptionGetProperty(sndDesc, kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_AudioChannelLayout, + channelLayoutSize, channelLayout, NULL); + require_noerr(err, bail); + + UInt32 channelNumber = AudioChannelLayoutTag_GetNumberOfChannels(channelLayout->mChannelLayoutTag); + if (!channelNumber) + channelNumber = channelLayout->mNumberChannelDescriptions; + + [(MP42AudioTrack*)newTrack setChannelLayoutTag: channelLayout->mChannelLayoutTag]; + + bail: + if (err) { + NSLog(@"Error: unable to read the sound description, guessing 1 channel"); + channelNumber = 1; + } + + [(MP42AudioTrack*)newTrack setChannels: channelNumber]; + + if (channelLayout) + free(channelLayout); + } + + // Text + else if ([mediaType isEqualToString:QTMediaTypeText]) { + if ([[track attributeForKey:QTTrackIDAttribute] integerValue] == _chapterId) { + newTrack = [[MP42ChapterTrack alloc] init]; + NSArray *chapters = [_sourceFile chapters]; + + for (NSDictionary *dic in chapters) { + QTTimeRange time = [[dic valueForKey:QTMovieChapterStartTime] QTTimeRangeValue]; + [(MP42ChapterTrack*)newTrack addChapter:[dic valueForKey:QTMovieChapterName] + duration:((float)time.time.timeValue / time.time.timeScale)*1000]; + } + } + } + + // Subtitle + else if([mediaType isEqualToString:@"sbtl"]) { + newTrack = [[MP42SubtitleTrack alloc] init]; + NSSize dimension = [track apertureModeDimensionsForMode:QTMovieApertureModeClean]; + [(MP42SubtitleTrack*)newTrack setTrackWidth: dimension.width]; + [(MP42SubtitleTrack*)newTrack setTrackHeight: dimension.height]; + [(MP42SubtitleTrack*)newTrack setWidth: dimension.width]; + [(MP42SubtitleTrack*)newTrack setHeight: dimension.height]; + } + + // Closed Caption + else if([mediaType isEqualToString:@"clcp"]) + newTrack = [[MP42ClosedCaptionTrack alloc] init]; + + else + newTrack = [[MP42Track alloc] init]; + + if (newTrack) { + newTrack.format = [self formatForTrack:track]; + newTrack.Id = [[track attributeForKey:QTTrackIDAttribute] integerValue]; + newTrack.sourceURL = _fileURL; + newTrack.name = [track attributeForKey:QTTrackDisplayNameAttribute]; + newTrack.language = [self langForTrack:track]; + + TimeValue64 duration = GetMediaDisplayDuration(media) / GetMediaTimeScale(media) * 1000; + newTrack.duration = duration; + + [_tracksArray addObject:newTrack]; + [newTrack release]; + } + } +} + +- (NSString*)formatForTrack: (QTTrack *)track; +{ + NSString* result = @""; + + ImageDescriptionHandle idh = (ImageDescriptionHandle) NewHandleClear(sizeof(ImageDescription)); + GetMediaSampleDescription([[track media] quickTimeMedia], 1, + (SampleDescriptionHandle)idh); + + switch ((*idh)->cType) { + case kH264CodecType: + result = MP42VideoFormatH264; + break; + case kMPEG4VisualCodecType: + result = MP42VideoFormatMPEG4Visual; + break; + case kSorensonCodecType: + result = MP42VideoFormatSorenson; + break; + case kSorenson3CodecType: + result = MP42VideoFormatSorenson3; + break; + case 'ap4h': + case 'apch': + case 'apcn': + case 'apcs': + case 'apco': + result = MP42VideoFormatProRes; + break; + case 'png ': + result = MP42VideoFormatPNG; + break; + case kAnimationCodecType: + result = MP42VideoFormatAnimation; + break; + case kAudioFormatMPEG4AAC: + case 'mp4a': + result = MP42AudioFormatAAC; + break; + case kAudioFormatMPEG4AAC_HE: + case kAudioFormatMPEG4AAC_HE_V2: + result = MP42AudioFormatHEAAC; + break; + case kAudioFormatLinearPCM: + case kRawCodecType: + case 'twos': + case 'sowt': + result = MP42AudioFormatPCM; + break; + case kAudioFormatAppleLossless: + result = MP42AudioFormatALAC; + break; + case kAudioFormatAC3: + case 'ms \0': + result = MP42AudioFormatAC3; + break; + case kAudioFormatMPEGLayer1: + case kAudioFormatMPEGLayer2: + case kAudioFormatMPEGLayer3: + case 'ms\0U': + result = MP42AudioFormatMP3; + break; + case kAudioFormatAMR: + result = MP42AudioFormatAMR; + break; + case TextMediaType: + result = MP42SubtitleFormatText; + break; + case kTx3gSampleType: + result = MP42SubtitleFormatTx3g; + break; + case 'SRT ': + result = MP42SubtitleFormatText; + break; + case 'SSA ': + result = MP42SubtitleFormatSSA; + break; + case 'c608': + result = MP42ClosedCaptionFormatCEA608; + break; + case kDVCNTSCCodecType: + case kDVCPALCodecType: + result = MP42VideoFormatDV; + break; + case 'm2v1': + result = MP42VideoFormatMPEG2; + break; + case kMotionJPEGACodecType: + case kMotionJPEGBCodecType: + result = MP42VideoFormatMotionJPEG; + break; + case TimeCodeMediaType: + result = MP42TimeCodeFormat; + break; + case kJPEGCodecType: + result = MP42VideoFormatJPEG; + break; + default: + result = @"Unknown"; + break; + } + DisposeHandle((Handle)idh); + + return result; +} + +- (NSString*)langForTrack: (QTTrack *)track +{ + long data = [[track attributeForKey:QTTrackLanguageAttribute] longValue]; + char code[4]; + NSString *language; + + language = [NSString stringWithUTF8String:lang_for_qtcode(data)->eng_name]; + + if ([language isEqualToString:@"Unknown"]) + { + code[0] = ((data & 0x7c00) >> 10) + 0x60; + code[1] = ((data & 0x03e0) >> 5) + 0x60; + code[2] = ((data & 0x001f) ) + 0x60; + code[3] = '\0'; + + language = [NSString stringWithFormat:@"%s", lang_for_code2(code)->eng_name]; + } + + return language; +} + +-(void)convertMetadata +{ + NSArray *items = nil; + NSDictionary *commonItemsDict = [NSDictionary dictionaryWithObjectsAndKeys:@"Name", QTMetadataCommonKeyTitle, + //nil, QTMetadataCommonKeyCreator, + //nil, QTMetadataCommonKeySubject, + @"Description", QTMetadataCommonKeyDescription, + @"Publisher", QTMetadataCommonKeyPublisher, + //nil, QTMetadataCommonKeyContributor, + @"Release Date", QTMetadataCommonKeyCreationDate, + //nil, QTMetadataCommonKeyLastModifiedDate, + @"Genre", QTMetadataCommonKeyType, + //nil, QTMetadataCommonKeyFormat, + //nil, QTMetadataCommonKeyIdentifier, + //nil, QTMetadataCommonKeySource, + //nil, QTMetadataCommonKeyLanguage, + //nil, QTMetadataCommonKeyRelation, + //nil, QTMetadataCommonKeyLocation, + @"Copyright", QTMetadataCommonKeyCopyrights, + @"Album", QTMetadataCommonKeyAlbumName, + //nil, QTMetadataCommonKeyAuthor, + //nil, QTMetadataCommonKeyArtwork + @"Artist", QTMetadataCommonKeyArtist, + //nil, QTMetadataCommonKeyMake, + //nil, QTMetadataCommonKeyModel, + @"Encoding Tool", QTMetadataCommonKeySoftware, + nil]; + + _metadata = [[MP42Metadata alloc] init]; + for (NSString *commonKey in [commonItemsDict allKeys]) { + items = [QTMetadataItem metadataItemsFromArray:[_sourceFile commonMetadata] withKey:[commonKey stringByReplacingOccurrencesOfString:@"@" withString:@"©"] keySpace:nil]; + if ([items count]) + [_metadata setTag:[[items lastObject] value] forKey:[commonItemsDict objectForKey:commonKey]]; + } + + items = [QTMetadataItem metadataItemsFromArray:[_sourceFile commonMetadata] withKey:[QTMetadataCommonKeyArtwork stringByReplacingOccurrencesOfString:@"@" withString:@"©"] keySpace:nil]; + if ([items count]) { + id artworkData = [[items lastObject] value]; + if ([artworkData isKindOfClass:[NSData class]]) { + NSImage *image = [[NSImage alloc] initWithData:artworkData]; + [_metadata.artworks addObject:[[[MP42Image alloc] initWithImage:image] autorelease]]; + [image release]; + } + } + + NSArray* availableMetadataFormats = [_sourceFile availableMetadataFormats]; + + if ([availableMetadataFormats containsObject:QTMetadataFormatiTunesMetadata]) { + NSArray* itunesMetadata = [_sourceFile metadataForFormat:QTMetadataFormatiTunesMetadata]; + + NSDictionary *itunesMetadataDict = [NSDictionary dictionaryWithObjectsAndKeys: + @"Album", QTMetadataiTunesMetadataKeyAlbum, + @"Artist", QTMetadataiTunesMetadataKeyArtist, + @"Comments", QTMetadataiTunesMetadataKeyUserComment, + //QTMetadataiTunesMetadataKeyCoverArt, + @"Copyright", QTMetadataiTunesMetadataKeyCopyright, + @"Release Date", QTMetadataiTunesMetadataKeyReleaseDate, + @"Encoded By", QTMetadataiTunesMetadataKeyEncodedBy, + //@"Genre", QTMetadataiTunesMetadataKeyPredefinedGenre, + @"Genre", QTMetadataiTunesMetadataKeyUserGenre, + @"Name", QTMetadataiTunesMetadataKeySongName, + @"Track Sub-Title", QTMetadataiTunesMetadataKeyTrackSubTitle, + @"Encoding Tool", QTMetadataiTunesMetadataKeyEncodingTool, + @"Composer", QTMetadataiTunesMetadataKeyComposer, + @"Album Artist", QTMetadataiTunesMetadataKeyAlbumArtist, + @"iTunes Account Type", QTMetadataiTunesMetadataKeyAccountKind, + @"iTunes Account", QTMetadataiTunesMetadataKeyAppleID, + @"artistID", QTMetadataiTunesMetadataKeyArtistID, + @"content ID", QTMetadataiTunesMetadataKeySongID, + @"Compilation", QTMetadataiTunesMetadataKeyDiscCompilation, + @"Disk #", QTMetadataiTunesMetadataKeyDiscNumber, + @"genreID", QTMetadataiTunesMetadataKeyGenreID, + @"Grouping", QTMetadataiTunesMetadataKeyGrouping, + @"playlistID", QTMetadataiTunesMetadataKeyPlaylistID, + @"Content Rating", QTMetadataiTunesMetadataKeyContentRating, + @"Rating", @"com.apple.iTunes.iTunEXTC", + @"Tempo", QTMetadataiTunesMetadataKeyBeatsPerMin, + @"Track #", QTMetadataiTunesMetadataKeyTrackNumber, + @"Art Director", QTMetadataiTunesMetadataKeyArtDirector, + @"Arranger", QTMetadataiTunesMetadataKeyArranger, + @"Lyricist", QTMetadataiTunesMetadataKeyAuthor, + @"Lyrics", QTMetadataiTunesMetadataKeyLyrics, + @"Acknowledgement", QTMetadataiTunesMetadataKeyAcknowledgement, + @"Conductor", QTMetadataiTunesMetadataKeyConductor, + @"Song Description", QTMetadataiTunesMetadataKeyDescription, + @"Description", @"desc", + @"Long Description", @"ldes", + @"Media Kind", @"stik", + @"TV Show", @"tvsh", + @"TV Episode #", @"tves", + @"TV Network", @"tvnn", + @"TV Episode ID", @"tven", + @"TV Season", @"tvsn", + @"HD Video", @"hdvd", + @"Gapless", @"pgap", + @"Sort Name", @"sonm", + @"Sort Artist", @"soar", + @"Sort Album Artist", @"soaa", + @"Sort Album", @"soal", + @"Sort Composer", @"soco", + @"Sort TV Show", @"sosn", + @"Category", @"catg", + @"iTunes U", @"itnu", + @"Purchase Date", @"purd", + @"Director", QTMetadataiTunesMetadataKeyDirector, + //QTMetadataiTunesMetadataKeyEQ, + @"Linear Notes", QTMetadataiTunesMetadataKeyLinerNotes, + @"Record Company", QTMetadataiTunesMetadataKeyRecordCompany, + @"Original Artist", QTMetadataiTunesMetadataKeyOriginalArtist, + @"Phonogram Rights", QTMetadataiTunesMetadataKeyPhonogramRights, + @"Producer", QTMetadataiTunesMetadataKeyProducer, + @"Performer", QTMetadataiTunesMetadataKeyPerformer, + @"Publisher", QTMetadataiTunesMetadataKeyPublisher, + @"Sound Engineer", QTMetadataiTunesMetadataKeySoundEngineer, + @"Soloist", QTMetadataiTunesMetadataKeySoloist, + @"Credits", QTMetadataiTunesMetadataKeyCredits, + @"Thanks", QTMetadataiTunesMetadataKeyThanks, + @"Online Extras", QTMetadataiTunesMetadataKeyOnlineExtras, + @"Executive Producer", QTMetadataiTunesMetadataKeyExecProducer, + nil]; + + for (NSString *itunesKey in [itunesMetadataDict allKeys]) { + items = [QTMetadataItem metadataItemsFromArray:itunesMetadata withKey:[itunesKey stringByReplacingOccurrencesOfString:@"@" withString:@"©"] keySpace:nil]; + if ([items count]) { + [_metadata setTag:[[items lastObject] value] forKey:[itunesMetadataDict objectForKey:itunesKey]]; + } + } + + items = [QTMetadataItem metadataItemsFromArray:itunesMetadata withKey:[QTMetadataiTunesMetadataKeyCoverArt stringByReplacingOccurrencesOfString:@"@" withString:@"©"] keySpace:nil]; + if ([items count]) { + id artworkData = [[items lastObject] value]; + if ([artworkData isKindOfClass:[NSData class]]) { + NSImage *image = [[NSImage alloc] initWithData:artworkData]; + [_metadata.artworks addObject:[[[MP42Image alloc] initWithImage:image] autorelease]]; + [image release]; + } + } + } + if ([availableMetadataFormats containsObject:QTMetadataFormatQuickTimeMetadata]) { + NSArray* quicktimeMetadata = [_sourceFile metadataForFormat:QTMetadataFormatQuickTimeMetadata]; + + NSDictionary *quicktimeMetadataDict = [NSDictionary dictionaryWithObjectsAndKeys: + @"Arist", QTMetadataQuickTimeMetadataKeyAuthor, + @"Comments", QTMetadataQuickTimeMetadataKeyComment, + @"Copyright", QTMetadataQuickTimeMetadataKeyCopyright, + @"Release Date", QTMetadataQuickTimeMetadataKeyCreationDate, + @"Director", QTMetadataQuickTimeMetadataKeyDirector, + @"Name", QTMetadataQuickTimeMetadataKeyDisplayName, + @"Description", QTMetadataQuickTimeMetadataKeyInformation, + @"Keyworkds", QTMetadataQuickTimeMetadataKeyKeywords, + @"Producer", QTMetadataQuickTimeMetadataKeyProducer, + @"Publisher", QTMetadataQuickTimeMetadataKeyPublisher, + @"Album", QTMetadataQuickTimeMetadataKeyAlbum, + @"Artist", QTMetadataQuickTimeMetadataKeyArtist, + @"Description", QTMetadataQuickTimeMetadataKeyDescription, + @"Encoding Tool",QTMetadataQuickTimeMetadataKeySoftware, + @"Genre", QTMetadataQuickTimeMetadataKeyGenre, + //QTMetadataQuickTimeMetadataKeyiXML, + @"Arranger", QTMetadataQuickTimeMetadataKeyArranger, + @"Encoded By", QTMetadataQuickTimeMetadataKeyEncodedBy, + @"Original Artist", QTMetadataQuickTimeMetadataKeyOriginalArtist, + @"Performer", QTMetadataQuickTimeMetadataKeyPerformer, + @"Composer", QTMetadataQuickTimeMetadataKeyComposer, + @"Credits", QTMetadataQuickTimeMetadataKeyCredits, + @"Phonogram Rights", QTMetadataQuickTimeMetadataKeyPhonogramRights, nil]; + + for (NSString *qtKey in [quicktimeMetadataDict allKeys]) { + items = [QTMetadataItem metadataItemsFromArray:quicktimeMetadata withKey:[qtKey stringByReplacingOccurrencesOfString:@"@" withString:@"©"] keySpace:nil]; + if ([items count]) { + [_metadata setTag:[[items lastObject] value] forKey:[quicktimeMetadataDict objectForKey:qtKey]]; + } + } + } + if ([availableMetadataFormats containsObject:QTMetadataFormatQuickTimeUserData]) { + NSArray* quicktimeUserDataMetadata = [_sourceFile metadataForFormat:QTMetadataFormatQuickTimeUserData]; + + NSDictionary *quicktimeUserDataMetadataDict = [NSDictionary dictionaryWithObjectsAndKeys: + @"Album", QTMetadataQuickTimeUserDataKeyAlbum, + @"Arranger", QTMetadataQuickTimeUserDataKeyArranger, + @"Artist", QTMetadataQuickTimeUserDataKeyArtist, + @"Lyricist", QTMetadataQuickTimeUserDataKeyAuthor, + @"Comments", QTMetadataQuickTimeUserDataKeyComment, + @"Composer", QTMetadataQuickTimeUserDataKeyComposer, + @"Copyright", QTMetadataQuickTimeUserDataKeyCopyright, + @"Release Date", QTMetadataQuickTimeUserDataKeyCreationDate, + @"Description", QTMetadataQuickTimeUserDataKeyDescription, + @"Director", QTMetadataQuickTimeUserDataKeyDirector, + @"Encoded By", QTMetadataQuickTimeUserDataKeyEncodedBy, + @"Name", QTMetadataQuickTimeUserDataKeyFullName, + @"Genre", QTMetadataQuickTimeUserDataKeyGenre, + @"Keywords", QTMetadataQuickTimeUserDataKeyKeywords, + @"Original Artist", QTMetadataQuickTimeUserDataKeyOriginalArtist, + @"Performer", QTMetadataQuickTimeUserDataKeyPerformers, + @"Producer", QTMetadataQuickTimeUserDataKeyProducer, + @"Publisher", QTMetadataQuickTimeUserDataKeyPublisher, + @"Online Extras", QTMetadataQuickTimeUserDataKeyURLLink, + @"Credits", QTMetadataQuickTimeUserDataKeyCredits, + @"Phonogram Rights", QTMetadataQuickTimeUserDataKeyPhonogramRights, nil]; + + for (NSString *qtUserDataKey in [quicktimeUserDataMetadataDict allKeys]) { + items = [QTMetadataItem metadataItemsFromArray:quicktimeUserDataMetadata withKey:[qtUserDataKey stringByReplacingOccurrencesOfString:@"@" withString:@"©"] keySpace:nil]; + if ([items count]) { + [_metadata setTag:[[items lastObject] value] forKey:[quicktimeUserDataMetadataDict objectForKey:qtUserDataKey]]; + } + } + } +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + Track qtTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack]; + Media media = GetTrackMedia(qtTrack); + + return GetMediaTimeScale(media); +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + MP42VideoTrack* currentTrack = (MP42VideoTrack*) track; + + return NSMakeSize([currentTrack width], [currentTrack height]); +} + +- (NSData*)magicCookieForTrack:(MP42Track *)track +{ + OSStatus err = noErr; + + QTTrack * qtTrack = [_sourceFile trackWithTrackID:[track sourceId]];; + NSString* mediaType = [qtTrack attributeForKey:QTTrackMediaTypeAttribute]; + Track qtcTrack = [qtTrack quickTimeTrack]; + Media media = GetTrackMedia(qtcTrack); + NSMutableData * magicCookie; + + // Get the sample description + SampleDescriptionHandle desc = (SampleDescriptionHandle) NewHandle(0); + GetMediaSampleDescription(media, 1, desc); + + if ([mediaType isEqualToString:QTMediaTypeVideo]) { + ImageDescriptionHandle imgDesc = (ImageDescriptionHandle) desc; + + if ((*imgDesc)->cType == kH264CodecType) { + // Get avcC atom + Handle imgDescHandle = NewHandle(0); + GetImageDescriptionExtension(imgDesc, &imgDescHandle, 'avcC', 1); + + magicCookie = [NSData dataWithBytes:*imgDescHandle length:GetHandleSize(imgDescHandle)]; + + DisposeHandle(imgDescHandle); + + return magicCookie; + } + else if ((*imgDesc)->cType == kMPEG4VisualCodecType) { + long count; + // Add ES decoder specific configuration + CountImageDescriptionExtensionType(imgDesc, 'esds', &count); + if (count >= 1) { + Handle imgDescExt = NewHandle(0); + UInt8* buffer; + int size; + + GetImageDescriptionExtension(imgDesc, &imgDescExt, 'esds', 1); + + ReadESDSDescExt(*imgDescExt, &buffer, &size, 1); + magicCookie = [NSData dataWithBytes:buffer length:size]; + + DisposeHandle(imgDescExt); + + return magicCookie; + } + } + } + else if ([mediaType isEqualToString:QTMediaTypeSound]) { + SoundDescriptionHandle sndDesc = (SoundDescriptionHandle) desc; + + AudioStreamBasicDescription asbd = {0}; + err = QTSoundDescriptionGetProperty(sndDesc, kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_AudioStreamBasicDescription, + sizeof(asbd), &asbd, NULL); + if (err) + return nil; + + if (asbd.mFormatID == kAudioFormatMPEG4AAC) { + // Get the magic cookie + UInt32 cookieSize; + void* cookie; + QTSoundDescriptionGetPropertyInfo(sndDesc, + kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_MagicCookie, + NULL, &cookieSize, NULL); + cookie = malloc(cookieSize); + QTSoundDescriptionGetProperty(sndDesc, + kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_MagicCookie, + cookieSize, cookie, &cookieSize); + // Extract DecoderSpecific info + UInt8* buffer; + int size; + ReadESDSDescExt(cookie, &buffer, &size, 0); + magicCookie = [NSData dataWithBytes:buffer length:size]; + + free(cookie); + free(buffer); + + return magicCookie; + + } + else if(asbd.mFormatID == kAudioFormatAppleLossless) { + // Get the magic cookie + UInt32 cookieSize; + void* cookie; + QTSoundDescriptionGetPropertyInfo(sndDesc, + kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_MagicCookie, + NULL, &cookieSize, NULL); + cookie = malloc(cookieSize); + QTSoundDescriptionGetProperty(sndDesc, + kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_MagicCookie, + cookieSize, cookie, &cookieSize); + if (cookieSize > 48) + // Remove unneeded parts of the cookie, as describred in ALACMagicCookieDescription.txt + magicCookie = [NSData dataWithBytes:cookie + 24 length:cookieSize - 32]; + else + magicCookie = [NSData dataWithBytes:cookie length:cookieSize]; + + free(cookie); + return magicCookie; + + } + else if (asbd.mFormatID == kAudioFormatAC3 || asbd.mFormatID == 0x6D732000) + { + ByteCount channelLayoutSize; + AudioChannelLayout* channelLayout = NULL; + err = QTSoundDescriptionGetPropertyInfo(sndDesc, kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_AudioChannelLayout, + NULL, &channelLayoutSize, NULL); + if (err) + return nil; + + channelLayout = (AudioChannelLayout*)malloc(channelLayoutSize); + + err = QTSoundDescriptionGetProperty(sndDesc, kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_AudioChannelLayout, + channelLayoutSize, channelLayout, NULL); + if (err) { + free(channelLayout); + return nil; + } + + UInt32 bitmapSize = sizeof(AudioChannelLayoutTag); + UInt32 channelBitmap; + err = AudioFormatGetProperty(kAudioFormatProperty_BitmapForLayoutTag, + sizeof(AudioChannelLayoutTag), &channelLayout->mChannelLayoutTag, + &bitmapSize, &channelBitmap); + + if (err && AudioChannelLayoutTag_GetNumberOfChannels(channelLayout->mChannelLayoutTag) == 6) + channelBitmap = 0x3F; + + uint8_t fscod = 0; + uint8_t bsid = 8; + uint8_t bsmod = 0; + uint8_t acmod = 7; + uint8_t lfeon = (channelBitmap & kAudioChannelBit_LFEScreen) ? 1 : 0; + uint8_t bit_rate_code = 15; + + switch (AudioChannelLayoutTag_GetNumberOfChannels(channelLayout->mChannelLayoutTag) - lfeon) { + case 1: + acmod = 1; + break; + case 2: + acmod = 2; + break; + case 3: + if (channelBitmap & kAudioChannelBit_CenterSurround) acmod = 3; + else acmod = 4; + break; + case 4: + if (channelBitmap & kAudioChannelBit_CenterSurround) acmod = 5; + else acmod = 6; + break; + case 5: + acmod = 7; + break; + default: + break; + } + + if (asbd.mSampleRate == 48000) fscod = 0; + else if (asbd.mSampleRate == 44100) fscod = 1; + else if (asbd.mSampleRate == 32000) fscod = 2; + else fscod = 3; + + NSMutableData *ac3Info = [[NSMutableData alloc] init]; + [ac3Info appendBytes:&fscod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsid length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&acmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&lfeon length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bit_rate_code length:sizeof(uint64_t)]; + + free(channelLayout); + + return [ac3Info autorelease]; + } + } + + return nil; +} + +- (AudioStreamBasicDescription)audioDescriptionForTrack:(MP42Track *)track +{ + OSStatus err = noErr; + NSString* mediaType = [[_sourceFile trackWithTrackID:[track sourceId]] attributeForKey:QTTrackMediaTypeAttribute]; + + Track qtcTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack]; + Media media = GetTrackMedia(qtcTrack); + + // Audio + if ([mediaType isEqualToString:QTMediaTypeSound]) { + // Get the sample description + SampleDescriptionHandle desc = (SampleDescriptionHandle) NewHandle(0); + GetMediaSampleDescription(media, 1, desc); + + SoundDescriptionHandle sndDesc = (SoundDescriptionHandle) desc; + + ByteCount formatDescSize; + AudioStreamBasicDescription formatDesc; + + err = QTSoundDescriptionGetPropertyInfo(sndDesc, kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_AudioStreamBasicDescription, + NULL, &formatDescSize, NULL); + require_noerr(err, bail); + + err = QTSoundDescriptionGetProperty(sndDesc, kQTPropertyClass_SoundDescription, + kQTSoundDescriptionPropertyID_AudioStreamBasicDescription, + formatDescSize, &formatDesc, NULL); + require_noerr(err, bail); + + bail: + if (err) { + NSLog(@"Error: unable to read the audio stream basic description"); + } + + return formatDesc; + } + + return [super audioDescriptionForTrack:track]; +} + +- (void)demux:(id)sender +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + OSStatus err = noErr; + + NSInteger tracksNumber = [_inputTracks count]; + NSInteger tracksDone = 0; + + MovDemuxHelper *demuxHelper = nil; + + for (MP42Track *track in _inputTracks) { + track.muxer_helper->demuxer_context = [[MovDemuxHelper alloc] init]; + + Track qtcTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack]; + Media media = GetTrackMedia(qtcTrack); + + demuxHelper = track.muxer_helper->demuxer_context; + demuxHelper->totalSampleNumber = GetMediaSampleCount(media); + } + + for (MP42Track * track in _inputTracks) { + if (_cancelled) + break; + + muxer_helper *helper = track.muxer_helper; + Track qtcTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack]; + Media media = GetTrackMedia(qtcTrack); + demuxHelper = helper->demuxer_context; + + // Create a QTSampleTable which contains all the informatio of the track samples. + TimeValue64 sampleTableStartDecodeTime = 0; + QTMutableSampleTableRef sampleTable = NULL; + err = CopyMediaMutableSampleTable(media, + 0, + &sampleTableStartDecodeTime, + 0, + 0, + &sampleTable); + require_noerr(err, bail); + + TimeValue64 minDisplayOffset = 0; + err = QTSampleTableGetProperty(sampleTable, + kQTPropertyClass_SampleTable, + kQTSampleTablePropertyID_MinDisplayOffset, + sizeof(TimeValue64), + &minDisplayOffset, + NULL); + require_noerr(err, bail); + + demuxHelper->minDisplayOffset = minDisplayOffset; + + SInt64 sampleIndex, sampleCount; + sampleCount = QTSampleTableGetNumberOfSamples(sampleTable); + + for (sampleIndex = 1; sampleIndex <= sampleCount && !_cancelled; sampleIndex++) { + TimeValue64 sampleDecodeTime = 0; + ByteCount sampleDataSize = 0; + MediaSampleFlags sampleFlags = 0; + UInt8 *sampleData = NULL; + TimeValue64 decodeDuration = QTSampleTableGetDecodeDuration(sampleTable, sampleIndex); + TimeValue64 displayOffset = QTSampleTableGetDisplayOffset(sampleTable, sampleIndex); + //uint32_t dflags = 0; + + // Get the frame's data size and sample flags. + SampleNumToMediaDecodeTime( media, sampleIndex, &sampleDecodeTime, NULL); + sampleDataSize = QTSampleTableGetDataSizePerSample(sampleTable, sampleIndex); + sampleFlags = QTSampleTableGetSampleFlags(sampleTable, sampleIndex); + /*dflags |= (sampleFlags & mediaSampleHasRedundantCoding) ? MP4_SDT_HAS_REDUNDANT_CODING : 0; + dflags |= (sampleFlags & mediaSampleHasNoRedundantCoding) ? MP4_SDT_HAS_NO_REDUNDANT_CODING : 0; + dflags |= (sampleFlags & mediaSampleIsDependedOnByOthers) ? MP4_SDT_HAS_DEPENDENTS : 0; + dflags |= (sampleFlags & mediaSampleIsNotDependedOnByOthers) ? MP4_SDT_HAS_NO_DEPENDENTS : 0; + dflags |= (sampleFlags & mediaSampleDependsOnOthers) ? MP4_SDT_IS_DEPENDENT : 0; + dflags |= (sampleFlags & mediaSampleDoesNotDependOnOthers) ? MP4_SDT_IS_INDEPENDENT : 0; + dflags |= (sampleFlags & mediaSampleEarlierDisplayTimesAllowed) ? MP4_SDT_EARLIER_DISPLAY_TIMES_ALLOWED : 0;*/ + + // Load the frame. + sampleData = malloc(sampleDataSize); + GetMediaSample2(media, sampleData, sampleDataSize, NULL, sampleDecodeTime, + NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL); + + demuxHelper->currentSampleId = demuxHelper->currentSampleId + 1; + demuxHelper->currentTime = demuxHelper->currentTime + decodeDuration; + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = sampleData; + sample->size = sampleDataSize; + sample->duration = decodeDuration; + sample->offset = displayOffset -minDisplayOffset; + sample->timestamp = demuxHelper->currentTime; + sample->isSync = !(sampleFlags & mediaSampleNotSync); + sample->trackId = track.sourceId; + + [self enqueue:sample]; + [sample release]; + + _progress = ((demuxHelper->currentSampleId / (CGFloat) demuxHelper->totalSampleNumber ) * 100 / tracksNumber) + + (tracksDone / (CGFloat) tracksNumber * 100); + } + + tracksDone++; + + bail: + QTSampleTableRelease(sampleTable); + } + + [self setDone:YES]; + [pool release]; +} + +- (void)startReading +{ + [super startReading]; + + if (!_demuxerThread && !_done) { + _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; + [_demuxerThread setName:@"QuickTime Demuxer"]; + [_demuxerThread start]; + } +} + +- (BOOL)cleanUp:(MP4FileHandle)fileHandle +{ + for (MP42Track *track in _outputsTracks) { + Track qtcTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack]; + MP42Track *inputTrack = [self inputTrackWithTrackID:track.sourceId]; + + TimeValue editTrackStart, editTrackDuration; + TimeValue64 editDisplayStart, trackDuration = 0; + Fixed editDwell; + + MovDemuxHelper *demuxHelper; + demuxHelper = inputTrack.muxer_helper->demuxer_context; + + // Find the first edit + // Each edit has a starting track timestamp, a duration in track time, a starting display timestamp and a rate. + GetTrackNextInterestingTime(qtcTrack, + nextTimeTrackEdit | nextTimeEdgeOK, + 0, + fixed1, + &editTrackStart, + &editTrackDuration); + + while (editTrackDuration > 0) { + editDisplayStart = TrackTimeToMediaTime(editTrackStart, qtcTrack); + editTrackDuration = (editTrackDuration / (double)GetMovieTimeScale([_sourceFile quickTimeMovie])) * MP4GetTimeScale(fileHandle); + editDwell = GetTrackEditRate64(qtcTrack, editTrackStart); + + if (demuxHelper->minDisplayOffset < 0 && editDisplayStart != -1) + MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, editDisplayStart - demuxHelper->minDisplayOffset, + editTrackDuration, !Fix2X(editDwell)); + else + MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, editDisplayStart, + editTrackDuration, !Fix2X(editDwell)); + + trackDuration += editTrackDuration; + // Find the next edit + GetTrackNextInterestingTime(qtcTrack, + nextTimeTrackEdit, + editTrackStart, + fixed1, + &editTrackStart, + &editTrackDuration); + } + + MP4SetTrackIntegerProperty(fileHandle, track.Id, "tkhd.duration", trackDuration); + } + + return YES; +} + +- (void) dealloc +{ + [_sourceFile release]; + + [super dealloc]; +} + +@end + +#endif diff --git a/MP42/MP42Sample.h b/MP42/MP42Sample.h new file mode 100644 index 0000000..3fbc959 --- /dev/null +++ b/MP42/MP42Sample.h @@ -0,0 +1,26 @@ +// +// MP42Sample.h +// Subler +// +// Created by Damiano Galassi on 29/06/10. +// Copyright 2010 Damiano Galassi. All rights reserved. +// + +#import + +@class MP42Track; + +@interface MP42SampleBuffer : NSObject { + @public + void *data; + uint64_t size; + uint64_t duration; + int64_t offset; + uint64_t timestamp; + uint32_t trackId; + BOOL isSync; + BOOL isCompressed; + BOOL isForced; +} + +@end diff --git a/MP42/MP42Sample.m b/MP42/MP42Sample.m new file mode 100644 index 0000000..33c98e9 --- /dev/null +++ b/MP42/MP42Sample.m @@ -0,0 +1,19 @@ +// +// MP42Sample.m +// Subler +// +// Created by Damiano Galassi on 29/06/10. +// Copyright 2010 Damiano Galassi. All rights reserved. +// + +#import "MP42Sample.h" + + +@implementation MP42SampleBuffer + +- (void)dealloc { + free(data); + [super dealloc]; +} + +@end diff --git a/MP42/MP42SrtImporter.h b/MP42/MP42SrtImporter.h new file mode 100644 index 0000000..4ba80b7 --- /dev/null +++ b/MP42/MP42SrtImporter.h @@ -0,0 +1,20 @@ +// +// MP42MkvFileImporter.h +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import +#import "MP42FileImporter.h" + +@class SBSubSerializer; + +@interface MP42SrtImporter : MP42FileImporter { + SBSubSerializer *_ss; + + BOOL _verticalPlacement; +} + +@end \ No newline at end of file diff --git a/MP42/MP42SrtImporter.m b/MP42/MP42SrtImporter.m new file mode 100644 index 0000000..9bbffd6 --- /dev/null +++ b/MP42/MP42SrtImporter.m @@ -0,0 +1,130 @@ +// +// MP42MkvFileImporter.m +// Subler +// +// Created by Damiano Galassi on 31/01/10. +// Copyright 2010 Damiano Galassi All rights reserved. +// + +#import "MP42SrtImporter.h" + +#import "MP42File.h" +#import "MP42SubUtilities.h" +#import "SBLanguages.h" + +@implementation MP42SrtImporter + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError +{ + if ((self = [super init])) { + _fileURL = [fileURL retain]; + + NSInteger trackCount = 1; + _tracksArray = [[NSMutableArray alloc] initWithCapacity:trackCount]; + + NSInteger success = 0; + MP4Duration duration = 0; + + MP42SubtitleTrack *newTrack = [[MP42SubtitleTrack alloc] init]; + + newTrack.format = MP42SubtitleFormatTx3g; + newTrack.sourceURL = _fileURL; + newTrack.alternate_group = 2; + newTrack.language = getFilenameLanguage((CFStringRef)[_fileURL path]); + + _ss = [[SBSubSerializer alloc] init]; + if ([[_fileURL pathExtension] caseInsensitiveCompare: @"srt"] == NSOrderedSame) { + success = LoadSRTFromPath([_fileURL path], _ss, &duration); + } else if ([[_fileURL pathExtension] caseInsensitiveCompare: @"smi"] == NSOrderedSame) { + success = LoadSMIFromPath([_fileURL path], _ss, 1); + } + + [newTrack setDuration:duration]; + + if (!success) { + if (outError) + *outError = MP42Error(@"The file could not be opened.", @"The file is not a srt file, or it does not contain any subtitles.", 100); + + [newTrack release]; + [self release]; + + return nil; + } + + [_ss setFinished:YES]; + + if ([_ss positionInformation]) { + newTrack.verticalPlacement = YES; + _verticalPlacement = YES; + } + if ([_ss forced]) + newTrack.someSamplesAreForced = YES; + + [_tracksArray addObject:newTrack]; + [newTrack release]; + } + + return self; +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + return 1000; +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + return NSMakeSize([(MP42SubtitleTrack*)track trackWidth], [(MP42SubtitleTrack*) track trackHeight]); +} + +- (void)demux:(id)sender +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + MP42SampleBuffer *sample; + + for (MP42SubtitleTrack *track in _inputTracks) { + CGSize trackSize; + trackSize.width = track.trackWidth; + trackSize.height = track.trackHeight; + + while (![_ss isEmpty] && !_cancelled) { + SBSubLine *sl = [_ss getSerializedPacket]; + + if ([sl->line isEqualToString:@"\n"]) { + sample = copyEmptySubtitleSample(track.sourceId, sl->end_time - sl->begin_time, NO); + } + else { + int top = (sl->top == INT_MAX) ? trackSize.height : sl->top; + sample = copySubtitleSample(track.sourceId, sl->line, sl->end_time - sl->begin_time, sl->forced, _verticalPlacement, trackSize, top); + } + + [self enqueue:sample]; + [sample release]; + } + } + + _progress = 100.0; + + [self setDone:YES]; + [pool release]; +} + +- (void)startReading +{ + [super startReading]; + + if (!_demuxerThread && !_done) { + _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; + [_demuxerThread setName:@"Srt Demuxer"]; + [_demuxerThread start]; + } +} + +- (void) dealloc +{ + [_ss release]; + + [super dealloc]; +} + +@end diff --git a/MP42/MP42SubUtilities.h b/MP42/MP42SubUtilities.h new file mode 100644 index 0000000..add21c6 --- /dev/null +++ b/MP42/MP42SubUtilities.h @@ -0,0 +1,80 @@ +// +// SubUtilities.h +// Subler +// +// Created by Alexander Strange on 7/24/07. +// Copyright 2007 Perian. All rights reserved. +// + +#import +#import +#import "mp4v2.h" + +@interface SBTextSample : NSObject { + MP4Duration timestamp; + NSString *title; +} + +@property(readwrite, retain) NSString *title; +@property(readwrite) MP4Duration timestamp; + +@end + +@interface SBSubLine : NSObject +{ +@public + NSString *line; + unsigned begin_time, end_time; + unsigned no; // line number, used only by SBSubSerializer + unsigned top; + unsigned forced; +} +-(id)initWithLine:(NSString*)l start:(unsigned)s end:(unsigned)e; +-(id)initWithLine:(NSString*)l start:(unsigned)s end:(unsigned)e top_pos:(unsigned)p forced:(unsigned)f; +@end + +@interface SBSubSerializer : NSObject +{ + // input lines, sorted by 1. beginning time 2. original insertion order + NSMutableArray *lines; + BOOL finished; + + BOOL position_information, forced; + unsigned last_begin_time, last_end_time; + unsigned linesInput; +} +-(void)addLine:(SBSubLine *)sline; +-(void)setFinished:(BOOL)finished; +-(SBSubLine*)getSerializedPacket; +-(BOOL)isEmpty; +-(BOOL)positionInformation; +-(void)setPositionInformation:(BOOL)info; +-(BOOL)forced; +-(void)setForced:(BOOL)info; +@end + +NSMutableString *STStandardizeStringNewlines(NSString *str); +extern NSString *STLoadFileWithUnknownEncoding(NSString *path); +int LoadSRTFromPath(NSString *path, SBSubSerializer *ss, MP4Duration *duration); +int LoadSMIFromPath(NSString *path, SBSubSerializer *ss, int subCount); + +int LoadChaptersFromPath(NSString *path, NSMutableArray *ss); +int ParseSSAHeader(NSString *header); +NSString *StripSSALine(NSString *line); + +unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSign); + +@class MP42SampleBuffer; + +MP42SampleBuffer* copySubtitleSample(MP4TrackId subtitleTrackId, NSString* string, MP4Duration duration, BOOL forced, BOOL verticalPlacement, CGSize trackSize, int top); +MP42SampleBuffer* copyEmptySubtitleSample(MP4TrackId subtitleTrackId, MP4Duration duration, BOOL forced); + +typedef struct { + // color format is 32-bit ARGB + UInt32 pixelColor[16]; + UInt32 duration; +} PacketControlData; + +int ExtractVobSubPacket(UInt8 *dest, UInt8 *framedSrc, int srcSize, int *usedSrcBytes, int index); +ComponentResult ReadPacketControls(UInt8 *packet, UInt32 palette[16], PacketControlData *controlDataOut,BOOL *forced); +Boolean ReadPacketTimes(uint8_t *packet, uint32_t length, uint16_t *startTime, uint16_t *endTime, uint8_t *forced); \ No newline at end of file diff --git a/MP42/MP42SubUtilities.m b/MP42/MP42SubUtilities.m new file mode 100644 index 0000000..7f860d0 --- /dev/null +++ b/MP42/MP42SubUtilities.m @@ -0,0 +1,1356 @@ +// +// SubUtilities.m +// Subler +// +// Created by Alexander Strange on 7/24/07. +// Copyright 2007 Perian. All rights reserved. +// + +#import "MP42SubUtilities.h" +#import "MP42Sample.h" +#import "MP42HtmlParser.h" + +#import "RegexKitLite.h" + +@implementation SBTextSample + +-(NSComparisonResult)compare:(SBTextSample *)otherObject +{ + MP4Duration otherTimestamp = [otherObject timestamp]; + + if (timestamp < otherTimestamp) + return NSOrderedAscending; + else if (timestamp > otherTimestamp) + return NSOrderedDescending; + + return NSOrderedSame; +} + +-(void) dealloc +{ + [title release]; + [super dealloc]; +} + +@synthesize timestamp; +@synthesize title; + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [coder encodeInt64:timestamp forKey:@"timestamp"]; + [coder encodeObject:title forKey:@"title"]; +} + +- (id)initWithCoder:(NSCoder *)decoder +{ + self = [super init]; + + timestamp = [decoder decodeInt64ForKey:@"timestamp"]; + title = [[decoder decodeObjectForKey:@"title"] retain]; + + return self; +} + +@end + +@implementation SBSubSerializer +-(id)init +{ + if ((self = [super init])) { + lines = [[NSMutableArray alloc] init]; + finished = NO; + last_begin_time = last_end_time = 0; + linesInput = 0; + } + + return self; +} + +-(void)dealloc +{ + [lines release]; + [super dealloc]; +} + +static CFComparisonResult CompareLinesByBeginTime(const void *a, const void *b, void *unused) +{ + SBSubLine *al = (SBSubLine*)a, *bl = (SBSubLine*)b; + + if (al->begin_time > bl->begin_time) return kCFCompareGreaterThan; + if (al->begin_time < bl->begin_time) return kCFCompareLessThan; + + if (al->no > bl->no) return kCFCompareGreaterThan; + if (al->no < bl->no) return kCFCompareLessThan; + return kCFCompareEqualTo; +} + +/*static int cmp_uint(const void *a, const void *b) +{ + unsigned av = *(unsigned*)a, bv = *(unsigned*)b; + + if (av > bv) return 1; + if (av < bv) return -1; + return 0; +}*/ + +-(void)addLine:(SBSubLine *)line +{ + if (line->begin_time >= line->end_time) { + if (line->begin_time) + //Codecprintf(NULL, "Invalid times (%d and %d) for line \"%s\"", line->begin_time, line->end_time, [line->line UTF8String]); + return; + } + + line->no = linesInput++; + + NSUInteger nlines = [lines count]; + + if (!nlines || line->begin_time > ((SBSubLine*)[lines objectAtIndex:nlines-1])->begin_time) { + [lines addObject:line]; + } else { + CFIndex i = CFArrayBSearchValues((CFArrayRef)lines, CFRangeMake(0, nlines), line, CompareLinesByBeginTime, NULL); + + if (i >= nlines) + [lines addObject:line]; + else + [lines insertObject:line atIndex:i]; + } + +} + +-(SBSubLine*)getNextRealSerializedPacket +{ + NSUInteger nlines = [lines count]; + SBSubLine *first = [lines objectAtIndex:0]; + NSMutableString *str; + int i; + + if (!finished) { + if (nlines > 1) { + unsigned maxEndTime = first->end_time; + + for (i = 1; i < nlines; i++) { + SBSubLine *l = [lines objectAtIndex:i]; + + if (l->begin_time >= maxEndTime) { + goto canOutput; + } + + maxEndTime = MAX(maxEndTime, l->end_time); + } + } + + return nil; + } + +canOutput: + str = [NSMutableString stringWithString:first->line]; + unsigned begin_time = last_end_time, end_time = first->end_time; + unsigned frcd = first->forced, top_pos = first->top; + int deleted = 0; + + for (i = 1; i < nlines; i++) { + SBSubLine *l = [lines objectAtIndex:i]; + if (l->begin_time >= end_time) break; + + //shorten packet end time if another shorter time (begin or end) is found + //as long as it isn't the begin time + end_time = MIN(end_time, l->end_time); + if (l->begin_time > begin_time) + end_time = MIN(end_time, l->begin_time); + + if (l->begin_time <= begin_time) + [str appendString:l->line]; + } + + for (i = 0; i < nlines; i++) { + SBSubLine *l = [lines objectAtIndex:i - deleted]; + + if (l->end_time == end_time) { + [lines removeObjectAtIndex:i - deleted]; + deleted++; + } + } + + return [[[SBSubLine alloc] initWithLine:str start:begin_time end:end_time top_pos:top_pos forced:frcd] autorelease]; +} + +-(SBSubLine*)getSerializedPacket +{ + int nlines = [lines count]; + + if (!nlines) return nil; + + SBSubLine *nextline = [lines objectAtIndex:0], *ret; + + if (nextline->begin_time > last_end_time) { + ret = [[[SBSubLine alloc] initWithLine:@"\n" start:last_end_time end:nextline->begin_time] autorelease]; + } else { + ret = [self getNextRealSerializedPacket]; + } + + if (!ret) return nil; + + last_begin_time = ret->begin_time; + last_end_time = ret->end_time; + + return ret; +} + +-(void)setFinished:(BOOL)_finished +{ + finished = _finished; +} + +-(BOOL)isEmpty +{ + return [lines count] == 0; +} + +-(BOOL)positionInformation +{ + return position_information; +} + +-(void)setPositionInformation:(BOOL)info +{ + position_information = info; +} + +-(BOOL)forced +{ + return forced; +} + +-(void)setForced:(BOOL)info +{ + forced = info; +} + +-(NSString*)description +{ + return [NSString stringWithFormat:@"lines left: %lu finished inputting: %d",(unsigned long)[lines count],finished]; +} +@end + +@implementation SBSubLine +-(id)initWithLine:(NSString*)l start:(unsigned)s end:(unsigned)e +{ + if ((self = [super init])) { + if ([l characterAtIndex:[l length]-1] != '\n') l = [l stringByAppendingString:@"\n"]; + line = [l retain]; + begin_time = s; + end_time = e; + no = 0; + } + + return self; +} + +-(id)initWithLine:(NSString*)l start:(unsigned)s end:(unsigned)e top_pos:(unsigned)p forced:(unsigned)f; +{ + if ((self = [self initWithLine:l start:s end:e])) { + top = p; + forced = f; + } + + return self; +} + +-(void)dealloc +{ + [line release]; + [super dealloc]; +} + +-(NSString*)description +{ + return [NSString stringWithFormat:@"\"%@\", from %d s to %d s",[line substringToIndex:[line length]-1],begin_time,end_time]; +} +@end + +unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSign) +{ + unsigned hour, minute, second, subsecond, timeval; + char separator; + int sign = 1; + + if (hasSign && *time == '-') { + sign = -1; + time++; + } + + if (sscanf(time,"%u:%u:%u%[,.:]%u",&hour,&minute,&second,&separator,&subsecond) < 5) + return 0; + + if (second > 60) + second = 0; + if (subsecond > secondScale) + subsecond = 0; + + timeval = hour * 60 * 60 + minute * 60 + second; + timeval = secondScale * timeval + subsecond; + + return timeval * sign; +} + +NSMutableString *STStandardizeStringNewlines(NSString *str) +{ + if(str == nil) + return nil; + NSMutableString *ms = [NSMutableString stringWithString:str]; + [ms replaceOccurrencesOfString:@"\r\n" withString:@"\n" options:0 range:NSMakeRange(0,[ms length])]; + [ms replaceOccurrencesOfString:@"\r" withString:@"\n" options:0 range:NSMakeRange(0,[ms length])]; + return ms; +} + +static const short frequencies[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1026, 29, -1258, 539, -930, -652, -815, -487, -2526, -2161, 146, -956, -914, 1149, -102, + 293, -2675, -923, -597, 339, 110, 247, 9, 0, 1024, 1239, 0, 0, 0, 0, 0, + 0, 1980, 1472, 1733, -304, -4086, 273, 582, 333, 2479, 1193, 5014, -1039, 1964, -2025, 1083, + -154, -5000, -1725, -4843, -366, -1850, -191, 1356, -2262, 1648, 1475, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, -458, 0, 0, 0, 0, 300, 0, 0, 300, 601, 0, + 0, 0, -2247, 0, 0, 0, 0, 0, 0, 0, 3667, 0, 0, 3491, 3567, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1993, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 1472, 0, 0, 0, 5000, 0, 601, 0, 1993, 0, + 0, 1083, 0, 672, -458, 0, 0, -458, 1409, 0, 0, 0, 0, 0, 1645, 425, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 601, -1123, + -1912, 4259, 2573, 8866, 55, 0, 0, -2247, -831, -3788, -3043, 0, 0, 3412, 2921, 1251, + 0, 0, 1377, 520, 1344, 0, -1123, 0, 0, -1213, 2208, -458, -794, 2636, 3824, 0}; + +BOOL SubDifferentiateLatin12(const unsigned char *data, int length) +{ + // generated from french/german (latin1) and hungarian/romanian (latin2) + + int frcount = 0; + + while (length--) { + frcount += frequencies[*data++]; + } + + return frcount <= 0; +} + + +extern NSString *STLoadFileWithUnknownEncoding(NSString *path) +{ + NSData *data = [NSData dataWithContentsOfMappedFile:path]; + + if (!data) + return nil; + + UniversalDetector *ud = [[UniversalDetector alloc] init]; + NSString *res = nil; + NSStringEncoding enc; + float conf; + NSString *enc_str; + BOOL latin2; + + [ud analyzeData:data]; + + enc = [ud encoding]; + conf = [ud confidence]; + enc_str = [ud MIMECharset]; + latin2 = enc == NSWindowsCP1250StringEncoding; + + if (latin2) { + if (SubDifferentiateLatin12([data bytes], [data length])) { // seems to actually be latin1 + enc = NSWindowsCP1252StringEncoding; + enc_str = @"windows-1252"; + } + } + + if ((conf < .6 || latin2) && enc != NSASCIIStringEncoding) { + NSLog(@"Guessed encoding \"%s\" for \"%s\", but not sure (confidence %f%%).\n",[enc_str UTF8String],[path UTF8String],conf*100.); + } + + res = [[[NSString alloc] initWithData:data encoding:enc] autorelease]; + + if (!res) { + if (latin2) { + NSLog(@"Encoding %s failed, retrying.\n",[enc_str UTF8String]); + enc = (enc == NSWindowsCP1252StringEncoding) ? NSWindowsCP1250StringEncoding : NSWindowsCP1252StringEncoding; + res = [[[NSString alloc] initWithData:data encoding:enc] autorelease]; + if (!res) NSLog(@"Both of latin1/2 failed.\n"); + } else { + res = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease]; + if (!res) NSLog(@"ASCII failed."), NSLog(@"Failed to load file as guessed encoding %@.",enc_str); + } + } + [ud release]; + + return res; +} + +static int ParsePosition(NSString *str) +{ + NSScanner *sc = [NSScanner scannerWithString:str]; + + int res = INT_MAX; + + if ([sc scanUpToString:@"X1:" intoString:nil]) { + [sc scanString:@"X1:" intoString:nil]; + [sc scanInt:&res]; + } + + return res; +} + +static int ParseForced(NSString *str) +{ + NSRange s = [str rangeOfString:@"!!!"]; + int res = 0; + + if (s.location != NSNotFound) + res = 1; + + return res; +} + +int LoadSRTFromPath(NSString *path, SBSubSerializer *ss, MP4Duration *duration) +{ + NSMutableString *srt = STStandardizeStringNewlines(STLoadFileWithUnknownEncoding(path)); + if (!srt) return 0; + + if ([srt characterAtIndex:0] == 0xFEFF) [srt deleteCharactersInRange:NSMakeRange(0,1)]; + if ([srt characterAtIndex:[srt length]-1] != '\n') [srt appendFormat:@"%c",'\n']; + + NSScanner *sc = [NSScanner scannerWithString:srt]; + NSString *res = nil; + [sc setCharactersToBeSkipped:nil]; + + unsigned startTime = 0, endTime = 0, forced = 0; + unsigned posCount = 0, forcedCount = 0; + signed position = INT_MAX; + + enum { + INITIAL, + TIMESTAMP, + LINES + } state = INITIAL; + + do { + switch (state) { + case INITIAL: + if ([sc scanInt:NULL] == TRUE && [sc scanUpToString:@"\n" intoString:&res] == FALSE) { + state = TIMESTAMP; + [sc scanString:@"\n" intoString:nil]; + } else + [sc setScanLocation:[sc scanLocation]+1]; + break; + case TIMESTAMP: + [sc scanUpToString:@" --> " intoString:&res]; + [sc scanString:@" --> " intoString:nil]; + startTime = ParseSubTime([res UTF8String], 1000, NO); + + [sc scanUpToString:@"\n" intoString:&res]; + [sc scanString:@"\n" intoString:nil]; + endTime = ParseSubTime([res UTF8String], 1000, NO); + position = ParsePosition(res); + forced = ParseForced(res); + if (position < INT_MAX) + posCount++; + if (forced) + forcedCount++; + + state = LINES; + break; + case LINES: + [sc scanUpToString:@"\n\n" intoString:&res]; + [sc scanString:@"\n\n" intoString:nil]; + SBSubLine *sl = [[SBSubLine alloc] initWithLine:res start:startTime end:endTime top_pos:position forced:forced]; + [ss addLine:[sl autorelease]]; + state = INITIAL; + break; + }; + } while (![sc isAtEnd]); + + if (posCount) + [ss setPositionInformation:YES]; + if (forcedCount) { + [ss setForced:YES]; + } + + *duration = endTime; + + return 1; +} + +int LoadChaptersFromPath(NSString *path, NSMutableArray *ss) +{ + NSMutableString *srt = STStandardizeStringNewlines(STLoadFileWithUnknownEncoding(path)); + if (!srt) return 0; + + if ([srt characterAtIndex:0] == 0xFEFF) [srt deleteCharactersInRange:NSMakeRange(0,1)]; + if ([srt characterAtIndex:[srt length]-1] != '\n') [srt appendFormat:@"%c",'\n']; + + NSScanner *sc = [NSScanner scannerWithString:srt]; + NSString *res=nil; + [sc setCharactersToBeSkipped:nil]; + + unsigned time=0; + int count = 1; + enum { + TIMESTAMP, + LINES + } state = TIMESTAMP; + + if ([srt characterAtIndex:0] == 'C') { // ogg tools format + do { + switch (state) { + case TIMESTAMP: + [sc scanUpToString:@"=" intoString:nil]; + [sc scanString:@"=" intoString:nil]; + [sc scanUpToString:@"\n" intoString:&res]; + [sc scanString:@"\n" intoString:nil]; + time = ParseSubTime([res UTF8String], 1000, NO); + + state = LINES; + break; + case LINES: + [sc scanUpToString:@"=" intoString:nil]; + [sc scanString:@"=" intoString:nil]; + if (!([sc scanUpToString:@"\n" intoString:&res])) + res = [NSString stringWithFormat:@"Chapter %d", count]; + [sc scanString:@"\n" intoString:nil]; + + SBTextSample *chapter = [[SBTextSample alloc] init]; + chapter.timestamp = time; + chapter.title = res; + + [ss addObject:chapter]; + count++; + + [chapter release]; + state = TIMESTAMP; + break; + }; + } while (![sc isAtEnd]); + } + else //mp4chaps format + { + do { + switch (state) { + case TIMESTAMP: + [sc scanUpToString:@" " intoString:&res]; + [sc scanString:@" " intoString:nil]; + time = ParseSubTime([res UTF8String], 1000, NO); + + state = LINES; + break; + case LINES: + if (!([sc scanUpToString:@"\n" intoString:&res])) + res = [NSString stringWithFormat:@"Chapter %d", count]; + + [sc scanString:@"\n" intoString:nil]; + + SBTextSample *chapter = [[SBTextSample alloc] init]; + chapter.timestamp = time; + chapter.title = res; + + [ss addObject:chapter]; + count++; + + [chapter release]; + state = TIMESTAMP; + break; + }; + } while (![sc isAtEnd]); + } + + return 1; +} + +static int parse_SYNC(NSString *str) +{ + NSScanner *sc = [NSScanner scannerWithString:str]; + + int res = 0; + + if ([sc scanString:@"START=" intoString:nil]) + [sc scanInt:&res]; + + return res; +} + +static NSArray *parse_STYLE(NSString *str) +{ + NSScanner *sc = [NSScanner scannerWithString:str]; + + NSString *firstRes; + NSString *secondRes; + NSArray *subArray; + int secondLoc; + + [sc scanUpToString:@"

" intoString:&firstRes]; + else + firstRes = @"noClass"; + + secondLoc = [str length] * .9; + [sc setScanLocation:secondLoc]; + + [sc scanUpToString:@"

" intoString:&secondRes]; + else + secondRes = @"noClass"; + + if ([firstRes isEqualToString:secondRes]) + secondRes = @"noClass"; + + subArray = [NSArray arrayWithObjects:firstRes, secondRes, nil]; + + return subArray; +} + +static int parse_P(NSString *str, NSArray *subArray) +{ + NSScanner *sc = [NSScanner scannerWithString:str]; + + NSString *res; + int subLang; + + if ([sc scanString:@"CLASS=" intoString:nil]) + [sc scanUpToString:@">" intoString:&res]; + else + res = @"noClass"; + + if ([res isEqualToString:[subArray objectAtIndex:0]]) + subLang = 1; + else if ([res isEqualToString:[subArray objectAtIndex:1]]) + subLang = 2; + else + subLang = 3; + + return subLang; +} + +static NSString *parse_COLOR(NSString *str) +{ + NSString *cvalue; + NSMutableString *cname = [NSMutableString stringWithString:str]; + + if (![str length]) return str; + + if ([cname characterAtIndex:0] == '#' && [cname lengthOfBytesUsingEncoding:NSASCIIStringEncoding] == 7) + cvalue = [NSString stringWithFormat:@"{\\1c&H%@%@%@&}", [cname substringWithRange:NSMakeRange(5,2)], [cname substringWithRange:NSMakeRange(3,2)], [cname substringWithRange:NSMakeRange(1,2)]]; + else { + [cname replaceOccurrencesOfString:@"Aqua" withString:@"00FFFF" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Black" withString:@"000000" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Blue" withString:@"0000FF" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Fuchsia" withString:@"FF00FF" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Gray" withString:@"808080" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Green" withString:@"008000" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Lime" withString:@"00FF00" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Maroon" withString:@"800000" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Navy" withString:@"000080" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Olive" withString:@"808000" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Purple" withString:@"800080" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Red" withString:@"FF0000" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Silver" withString:@"C0C0C0" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Teal" withString:@"008080" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"White" withString:@"FFFFFF" options:1 range:NSMakeRange(0,[cname length])]; + [cname replaceOccurrencesOfString:@"Yellow" withString:@"FFFF00" options:1 range:NSMakeRange(0,[cname length])]; + + if ([cname lengthOfBytesUsingEncoding:NSASCIIStringEncoding] == 6) + cvalue = [NSString stringWithFormat:@"{\\1c&H%@%@%@&}", [cname substringWithRange:NSMakeRange(4,2)], [cname substringWithRange:NSMakeRange(2,2)], [cname substringWithRange:NSMakeRange(0,2)]]; + else + cvalue = @"{\\1c&HFFFFFF&}"; + } + + return cvalue; +} + +static NSString *parse_FONT(NSString *str) +{ + NSScanner *sc = [NSScanner scannerWithString:str]; + + NSString *res; + NSString *color; + + if ([sc scanString:@"COLOR=" intoString:nil]) { + [sc scanUpToString:@">" intoString:&res]; + color = parse_COLOR(res); + } + else + color = @"{\\1c&HFFFFFF&}"; + + return color; +} + +static NSMutableString *StandardizeSMIWhitespace(NSString *str) +{ + if (!str) return nil; + NSMutableString *ms = [NSMutableString stringWithString:str]; + [ms replaceOccurrencesOfString:@"\r" withString:@"" options:0 range:NSMakeRange(0,[ms length])]; + [ms replaceOccurrencesOfString:@"\n" withString:@"" options:0 range:NSMakeRange(0,[ms length])]; + [ms replaceOccurrencesOfString:@" " withString:@" " options:0 range:NSMakeRange(0,[ms length])]; + return ms; +} + +int LoadSMIFromPath(NSString *path, SBSubSerializer *ss, int subCount) +{ + NSMutableString *smi = StandardizeSMIWhitespace(STLoadFileWithUnknownEncoding(path)); + if (!smi) return 0; + + NSScanner *sc = [NSScanner scannerWithString:smi]; + NSString *res = nil; + [sc setCharactersToBeSkipped:nil]; + [sc setCaseSensitive:NO]; + + NSMutableString *cmt = [NSMutableString string]; + NSArray *subLanguage = parse_STYLE(smi); + + int startTime=-1, endTime=-1, syncTime=-1; + int cc=1; + + enum { + TAG_INIT, + TAG_SYNC, + TAG_P, + TAG_BR_OPEN, + TAG_BR_CLOSE, + TAG_B_OPEN, + TAG_B_CLOSE, + TAG_I_OPEN, + TAG_I_CLOSE, + TAG_FONT_OPEN, + TAG_FONT_CLOSE, + TAG_COMMENT + } state = TAG_INIT; + + do { + switch (state) { + case TAG_INIT: + [sc scanUpToString:@"" intoString:&res]; + syncTime = parse_SYNC(res); + if (startTime > -1) { + endTime = syncTime; + if (subCount == 2 && cc == 2) + [cmt insertString:@"{\\an8}" atIndex:0]; + if ((subCount == 1 && cc == 1) || (subCount == 2 && cc == 2)) { + SBSubLine *sl = [[SBSubLine alloc] initWithLine:cmt start:startTime end:endTime]; + [ss addLine:[sl autorelease]]; + } + } + startTime = syncTime; + [cmt setString:@""]; + state = TAG_COMMENT; + break; + case TAG_P: + [sc scanUpToString:@">" intoString:&res]; + cc = parse_P(res, subLanguage); + [cmt setString:@""]; + state = TAG_COMMENT; + break; + case TAG_BR_OPEN: + [sc scanUpToString:@">" intoString:nil]; + [cmt appendString:@"\\n"]; + state = TAG_COMMENT; + break; + case TAG_BR_CLOSE: + [sc scanUpToString:@">" intoString:nil]; + [cmt appendString:@"\\n"]; + state = TAG_COMMENT; + break; + case TAG_B_OPEN: + [sc scanUpToString:@">" intoString:&res]; + [cmt appendString:@"{\\b1}"]; + state = TAG_COMMENT; + break; + case TAG_B_CLOSE: + [sc scanUpToString:@">" intoString:nil]; + [cmt appendString:@"{\\b0}"]; + state = TAG_COMMENT; + break; + case TAG_I_OPEN: + [sc scanUpToString:@">" intoString:&res]; + [cmt appendString:@"{\\i1}"]; + state = TAG_COMMENT; + break; + case TAG_I_CLOSE: + [sc scanUpToString:@">" intoString:nil]; + [cmt appendString:@"{\\i0}"]; + state = TAG_COMMENT; + break; + case TAG_FONT_OPEN: + [sc scanUpToString:@">" intoString:&res]; + [cmt appendString:parse_FONT(res)]; + state = TAG_COMMENT; + break; + case TAG_FONT_CLOSE: + [sc scanUpToString:@">" intoString:nil]; + [cmt appendString:@"{\\1c&HFFFFFF&}"]; + state = TAG_COMMENT; + break; + case TAG_COMMENT: + [sc scanString:@">" intoString:nil]; + if ([sc scanUpToString:@"<" intoString:&res]) + [cmt appendString:res]; + else + [cmt appendString:@"<>"]; + if ([sc scanString:@"<" intoString:nil]) { + if ([sc scanString:@"SYNC" intoString:nil]) { + state = TAG_SYNC; + break; + } + else if ([sc scanString:@"P" intoString:nil]) { + state = TAG_P; + break; + } + else if ([sc scanString:@"BR" intoString:nil]) { + state = TAG_BR_OPEN; + break; + } + else if ([sc scanString:@"/BR" intoString:nil]) { + state = TAG_BR_CLOSE; + break; + } + else if ([sc scanString:@"B" intoString:nil]) { + state = TAG_B_OPEN; + break; + } + else if ([sc scanString:@"/B" intoString:nil]) { + state = TAG_B_CLOSE; + break; + } + else if ([sc scanString:@"I" intoString:nil]) { + state = TAG_I_OPEN; + break; + } + else if ([sc scanString:@"/I" intoString:nil]) { + state = TAG_I_CLOSE; + break; + } + else if ([sc scanString:@"FONT" intoString:nil]) { + state = TAG_FONT_OPEN; + break; + } + else if ([sc scanString:@"/FONT" intoString:nil]) { + state = TAG_FONT_CLOSE; + break; + } + else { + [cmt appendString:@"<"]; + state = TAG_COMMENT; + break; + } + } + } + } while (![sc isAtEnd]); + return 1; +} + +int ParseSSAHeader(NSString *header) { + NSString *info; + NSString *styles; + //NSString *splitLine = @"\\n+"; + //NSArray * stylesArray; + + //NSLog(@"%@", header); + NSScanner *sc = [NSScanner scannerWithString:header]; + [sc setCharactersToBeSkipped:nil]; + + [sc scanUpToString:@"[V4+ Styles]" intoString:&info]; + if (info) { + } + [sc scanUpToString:@"[Events]" intoString:&styles]; + if (styles) { + //stylesArray = [styles componentsSeparatedByRegex:splitLine]; + //NSLog(@"%@", styles); + } + [sc scanUpToString:@"Format:" intoString:nil]; + + return 0; +} + +NSString* StripSSALine(NSString *line){ + NSUInteger i = 0; + + NSScanner *sc = [NSScanner scannerWithString:line]; + for (i = 0; i < 8; i++) { + [sc scanUpToString:@"," intoString:nil]; + [sc scanString:@"," intoString:nil]; + } + + line = [[sc string]substringFromIndex:[sc scanLocation]]; + + NSRange startRange = [line rangeOfString: @"}"]; + while (startRange.location != NSNotFound) { + NSRange endRange = [line rangeOfString: @"{"]; + if (endRange.location != NSNotFound && endRange.length != 0) { + NSString * replacement = @""; + if (endRange.location + 3 < [line length]) { + unichar tag = [line characterAtIndex:endRange.location + 2]; + unichar tagState = [line characterAtIndex:endRange.location + 3]; + if (tagState == '1') { + if (tag == 'i') replacement = @""; + else if (tag == 'b') replacement = @""; + else if (tag == 'u') replacement = @""; + } + else if (tagState == '0'){ + if (tag == 'i') replacement = @""; + else if (tag == 'b') replacement = @""; + else if (tag == 'u') replacement = @""; + } + } + endRange.length = startRange.location - endRange.location +1; + line = [line stringByReplacingCharactersInRange:endRange withString:replacement]; + startRange = [line rangeOfString: @"}"]; + } + else + break; + } + + startRange = [line rangeOfString: @"\\N"]; + while (startRange.location != NSNotFound) { + startRange.length = 2; + line = [line stringByReplacingCharactersInRange:startRange withString:@"\n"]; + startRange = [line rangeOfString: @"\\N"]; + } + + startRange = [line rangeOfString: @"\\n"]; + while (startRange.location != NSNotFound) { + startRange.length = 2; + line = [line stringByReplacingCharactersInRange:startRange withString:@"\n"]; + startRange = [line rangeOfString: @"\\n"]; + } + + return line; +} + +u_int8_t* createStyleRecord(u_int16_t startChar, u_int16_t endChar, u_int16_t fontID, u_int8_t flags, rgba_color color, u_int8_t* style) +{ + style[0] = (startChar >> 8) & 0xff; // startChar + style[1] = startChar & 0xff; + style[2] = (endChar >> 8) & 0xff; // endChar + style[3] = endChar & 0xff; + style[4] = (fontID >> 8) & 0xff; // font-ID + style[5] = fontID & 0xff; + style[6] = flags; // face-style-flags: 1 bold; 2 italic; 4 underline + style[7] = 24; // font-size + style[8] = color.r; // r + style[9] = color.g; // g + style[10] = color.b; // b + style[11] = color.a; // a + + return style; +} + +size_t closeStyleAtom(u_int16_t styleCount, u_int8_t* styleAtom) +{ + size_t styleSize = 10 + (styleCount * 12); + styleAtom[0] = 0; + styleAtom[1] = 0; + styleAtom[2] = (styleSize >> 8) & 0xff; + styleAtom[3] = styleSize & 0xff; + styleAtom[8] = (styleCount >> 8) & 0xff; + styleAtom[9] = styleCount & 0xff; + + return styleSize; +} + +NSString* createStyleAtomForString(NSString* string, u_int8_t** buffer, size_t *size) +{ + MP42HtmlParser *parser = [[MP42HtmlParser alloc] initWithString:string]; + parser.defaultColor = make_color(255, 255, 255, 255); + + while ([parser parseNextTag] != NSNotFound); + + [parser serializeStyles]; + + *buffer = malloc(sizeof(u_int8_t) * 12 * [parser.styles count] + 10); + u_int16_t styleCount = 0; + memcpy(*buffer + 4, "styl", 4); + + for (MP42Style *style in parser.styles) { + u_int8_t styleRecord[12]; + createStyleRecord(style.location, style.location + style.length, 1, style.style, style.color, styleRecord); + memcpy(*buffer + 10 + (12 * styleCount), styleRecord, 12); + styleCount++; + } + + if (styleCount) + *size = closeStyleAtom(styleCount, *buffer); + + string = [parser.text retain]; + [parser release]; + + return [string autorelease]; +} + +NSString* removeNewLines(NSString* string) { + NSMutableString *mutableString = [NSMutableString stringWithString:string]; + + [mutableString replaceOccurrencesOfString:@"\r\n" withString:@"\n" options:0 range:NSMakeRange(0,[mutableString length])]; + [mutableString replaceOccurrencesOfString:@"\r" withString:@"\n" options:0 range:NSMakeRange(0,[mutableString length])]; + + while ([mutableString length] && [mutableString characterAtIndex:[mutableString length] - 1] == '\n') + [mutableString deleteCharactersInRange:NSMakeRange([mutableString length] -1, 1)]; + + NSMutableString *mutableString2 = [NSMutableString stringWithString:mutableString]; + + NSUInteger replacedCount = [mutableString2 replaceOccurrencesOfString:@"\n" withString:@" " options:0 range:NSMakeRange(0,[mutableString2 length])]; + if (replacedCount >= 2) + return mutableString2; + else + return mutableString; +} + +void createForcedAtom(u_int8_t* buffer) { + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 8; + buffer[4] = 'f'; + buffer[5] = 'r'; + buffer[6] = 'c'; + buffer[7] = 'd'; +} + +void createTboxAtom(u_int8_t* buffer, u_int16_t top, u_int16_t left, u_int16_t bottom, u_int16_t right) { + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 16; + buffer[4] = 't'; + buffer[5] = 'b'; + buffer[6] = 'o'; + buffer[7] = 'x'; + buffer[8] = top >> 8; + buffer[9] = top & 0xFF; + buffer[10] = left >> 8; + buffer[11] = left & 0xFF; + buffer[12] = bottom >> 8; + buffer[13] = bottom & 0xFF; + buffer[14] = right >> 8; + buffer[15] = right & 0xFF; +} + +MP42SampleBuffer* copySubtitleSample(MP4TrackId subtitleTrackId, NSString *string, MP4Duration duration, BOOL forced, BOOL verticalPlacement, CGSize trackSize, int top) +{ + u_int8_t *sampleData = NULL, *styleAtom = NULL; + size_t styleSize = 0, sampleSize = 0, stringLength = 0; + u_int64_t pos = 0; + + string = removeNewLines(string); + string = createStyleAtomForString(string, &styleAtom, &styleSize); + + stringLength = strlen([string UTF8String]); + sampleSize = 2 + (stringLength * sizeof(char)) + styleSize + (forced == 1 ? 8 : 0) + (verticalPlacement == 1 ? 16 : 0); + sampleData = malloc(sampleSize); + + pos = 2; + + if (stringLength) { + memcpy(sampleData + pos, [string UTF8String], stringLength); + pos += stringLength; + } + + if (styleSize) { + memcpy(sampleData + pos, styleAtom, styleSize); + pos += styleSize; + } + + // Add a frcd atom + if (forced) { + u_int8_t forcedAtom[8]; + createForcedAtom(forcedAtom); + + memcpy(sampleData + pos, forcedAtom, 8); + pos += 8; + } + + // Add a tbox atom with offset from top + if (verticalPlacement) { + u_int8_t tboxAtom[16]; + if (top == 0) + createTboxAtom(tboxAtom, top, 0, trackSize.height * 0.12, trackSize.width); + else + createTboxAtom(tboxAtom, trackSize.height * 0.88, 0, trackSize.height, trackSize.width); + + memcpy(sampleData + pos, tboxAtom, 16); + } + + sampleData[0] = (stringLength >> 8) & 0xff; + sampleData[1] = stringLength & 0xff; + + free(styleAtom); + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = sampleData; + sample->size = sampleSize; + sample->duration = duration; + sample->offset = 0; + sample->timestamp = duration; + sample->isSync = true; + sample->trackId = subtitleTrackId; + + return sample; +} + +MP42SampleBuffer* copyEmptySubtitleSample(MP4TrackId subtitleTrackId, MP4Duration duration, BOOL forced) +{ + uint8_t *sampleData = NULL; + u_int8_t empty[2] = {0,0}; + + sampleData = malloc(2); + memcpy(sampleData, empty, 2); + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = sampleData; + sample->size = 2; + sample->duration = duration; + sample->offset = 0; + sample->timestamp = duration; + sample->isSync = true; + sample->trackId = subtitleTrackId; + + return sample; +} + +/* VobSub related */ +int ExtractVobSubPacket(UInt8 *dest, UInt8 *framedSrc, int srcSize, int *usedSrcBytes, int index) { + int copiedBytes = 0; + UInt8 *currentPacket = framedSrc; + int packetSize = INT_MAX; + + while (currentPacket - framedSrc < srcSize && copiedBytes < packetSize) { + // 3-byte start code: 0x00 00 01 + if (currentPacket[0] + currentPacket[1] != 0 || currentPacket[2] != 1) { + //Codecprintf(NULL, "VobSub Codec: !! Unknown header: %02x %02x %02x\n", currentPacket[0], currentPacket[1], currentPacket[2]); + return copiedBytes; + } + + int packet_length; + + switch (currentPacket[3]) { + case 0xba: + // discard PS packets; nothing in them we're interested in + // here, packet_length is the additional stuffing + packet_length = currentPacket[13] & 0x7; + + currentPacket += 14 + packet_length; + break; + + case 0xbe: + case 0xbf: + // skip padding and navigation data + // (navigation shouldn't be present anyway) + packet_length = currentPacket[4]; + packet_length <<= 8; + packet_length += currentPacket[5]; + + currentPacket += 6 + packet_length; + break; + + case 0xbd: + // a private stream packet, contains subtitle data + packet_length = currentPacket[4]; + packet_length <<= 8; + packet_length += currentPacket[5]; + + int header_data_length = currentPacket[8]; + int packetIndex = currentPacket[header_data_length + 9] & 0x1f; + if(index == -1) + index = packetIndex; + if(index == packetIndex) + { + int blockSize = packet_length - 1 - (header_data_length + 3); + memcpy(&dest[copiedBytes], + // header's 9 bytes + extension, we don't want 1st byte of packet + ¤tPacket[9 + header_data_length + 1], + // we don't want the 1-byte stream ID, or the header + blockSize); + copiedBytes += blockSize; + + if(packetSize == INT_MAX) + { + packetSize = dest[0] << 8 | dest[1]; + } + } + currentPacket += packet_length + 6; + break; + + default: + // unknown packet, probably video, return for now + //Codecprintf(NULL, "VobSubCodec - Unknown packet type %x, aborting\n", (int)currentPacket[3]); + return copiedBytes; + } // switch (currentPacket[3]) + } // while (currentPacket - framedSrc < srcSize) + if(usedSrcBytes != NULL) + *usedSrcBytes = currentPacket - framedSrc; + + return copiedBytes; +} + +ComponentResult ReadPacketControls(UInt8 *packet, UInt32 palette[16], PacketControlData *controlDataOut,BOOL *forced) { + // to set whether the key sequences 0x03 - 0x06 have been seen + UInt16 controlSeqSeen = 0; + int i = 0; + Boolean loop = TRUE; + int controlOffset = (packet[2] << 8) + packet[3] + 4; + uint8_t *controlSeq = packet + controlOffset; + + memset(controlDataOut, 0, sizeof(PacketControlData)); + + while (loop) { + switch (controlSeq[i]) { + case 0x00: + // subpicture identifier, we don't care + *forced = YES; + i++; + break; + + case 0x01: + // start displaying, we don't care + i++; + break; + + case 0x03: + // palette info + controlDataOut->pixelColor[3] += palette[controlSeq[i+1] >> 4 ]; + controlDataOut->pixelColor[2] += palette[controlSeq[i+1] & 0xf]; + controlDataOut->pixelColor[1] += palette[controlSeq[i+2] >> 4 ]; + controlDataOut->pixelColor[0] += palette[controlSeq[i+2] & 0xf]; + + i += 3; + controlSeqSeen |= 0x0f; + break; + + case 0x04: + // alpha info + controlDataOut->pixelColor[3] += (controlSeq[i + 1] & 0xf0) << 20; + controlDataOut->pixelColor[2] += (controlSeq[i + 1] & 0x0f) << 24; + controlDataOut->pixelColor[1] += (controlSeq[i + 2] & 0xf0) << 20; + controlDataOut->pixelColor[0] += (controlSeq[i + 2] & 0x0f) << 24; + + // double the nibble + controlDataOut->pixelColor[3] += (controlSeq[i + 1] & 0xf0) << 24; + controlDataOut->pixelColor[2] += (controlSeq[i + 1] & 0x0f) << 28; + controlDataOut->pixelColor[1] += (controlSeq[i + 2] & 0xf0) << 24; + controlDataOut->pixelColor[0] += (controlSeq[i + 2] & 0x0f) << 28; + + i += 3; + controlSeqSeen |= 0xf0; + break; + + case 0x05: + // coordinates of image, ffmpeg takes care of this + i += 7; + break; + + case 0x06: + // offset of the first graphic line, and second, ffmpeg takes care of this + i += 5; + break; + + case 0xff: + // end of control sequence + loop = FALSE; + break; + + default: + NSLog(@"!! Unknown control sequence 0x%02x aborting (offset %x)\n", controlSeq[i], i); + loop = FALSE; + break; + } + } + + // force fully transparent to transparent black; needed? for graphicsModePreBlackAlpha + for (i = 0; i < 4; i++) { + if ((controlDataOut->pixelColor[i] & 0xff000000) == 0) + controlDataOut->pixelColor[i] = 0; + } + + if (controlSeqSeen != 0xff) + return -1; + return noErr; +} + +Boolean ReadPacketTimes(uint8_t *packet, uint32_t length, uint16_t *startTime, uint16_t *endTime, uint8_t *forced) { + // to set whether the key sequences 0x01 - 0x02 have been seen + Boolean loop = TRUE; + *startTime = *endTime = 0; + *forced = 0; + + int controlOffset = (packet[2] << 8) + packet[3]; + while(loop) + { + if(controlOffset > length) + return NO; + uint8_t *controlSeq = packet + controlOffset; + int32_t i = 4; + int32_t end = length - controlOffset; + uint16_t timestamp = (controlSeq[0] << 8) | controlSeq[1]; + uint16_t nextOffset = (controlSeq[2] << 8) + controlSeq[3]; + while (i < end) { + switch (controlSeq[i]) { + case 0x00: + *forced = 1; + i++; + break; + + case 0x01: + *startTime = (timestamp << 10) / 90; + i++; + break; + + case 0x02: + *endTime = (timestamp << 10) / 90; + i++; + loop = false; + break; + + case 0x03: + // palette info, we don't care + i += 3; + break; + + case 0x04: + // alpha info, we don't care + i += 3; + break; + + case 0x05: + // coordinates of image, ffmpeg takes care of this + i += 7; + break; + + case 0x06: + // offset of the first graphic line, and second, ffmpeg takes care of this + i += 5; + break; + + case 0xff: + // end of control sequence + if(controlOffset == nextOffset) + loop = false; + controlOffset = nextOffset; + i = INT_MAX; + break; + + default: + return NO; + break; + } + } + if(i != INT_MAX) + { + //End of packet + loop = false; + } + } + return YES; +} diff --git a/MP42/MP42SubtitleTrack.h b/MP42/MP42SubtitleTrack.h new file mode 100644 index 0000000..bae81cc --- /dev/null +++ b/MP42/MP42SubtitleTrack.h @@ -0,0 +1,30 @@ +// +// MP42SubtitleTrack.h +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import +#import "MP42VideoTrack.h" + +@interface MP42SubtitleTrack : MP42VideoTrack { + BOOL _verticalPlacement; + BOOL _someSamplesAreForced; + BOOL _allSamplesAreForced; + + MP42TrackId _forcedTrackId; + MP42Track *_forcedTrack; +} + +- (BOOL)exportToURL:(NSURL *)url error:(NSError **)error; + +@property(nonatomic, readwrite) BOOL verticalPlacement; +@property(nonatomic, readwrite) BOOL someSamplesAreForced; +@property(nonatomic, readwrite) BOOL allSamplesAreForced; + +@property(nonatomic, readonly) MP42TrackId forcedTrackId; +@property(nonatomic, readwrite, assign) MP42Track *forcedTrack; + +@end diff --git a/MP42/MP42SubtitleTrack.m b/MP42/MP42SubtitleTrack.m new file mode 100644 index 0000000..de743a8 --- /dev/null +++ b/MP42/MP42SubtitleTrack.m @@ -0,0 +1,436 @@ +// +// MP42SubtitleTrack.m +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import "MP42SubtitleTrack.h" +#import "MP42Utilities.h" +#import "MP42MediaFormat.h" +#import "MP42HtmlParser.h" +#import "SBLanguages.h" + +@implementation MP42SubtitleTrack + +- (instancetype)initWithSourceURL:(NSURL *)URL trackID:(NSInteger)trackID fileHandle:(MP4FileHandle)fileHandle +{ + if ((self = [super initWithSourceURL:URL trackID:trackID fileHandle:fileHandle])) { + if (![_format isEqualToString:MP42SubtitleFormatVobSub]) { + _mediaType = MP42MediaTypeSubtitle; + + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.tx3g.defTextBoxBottom", &height); + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.tx3g.defTextBoxRight", &width); + + uint64_t displayFlags = 0; + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.tx3g.displayFlags", &displayFlags); + + if (displayFlags) { + if ((displayFlags & 0x20000000) == 0x20000000) + _verticalPlacement = YES; + if ((displayFlags & 0x40000000) == 0x40000000) + _someSamplesAreForced = YES; + if ((displayFlags & 0x80000000) == 0x80000000) + _allSamplesAreForced = YES; + } + + if (MP4HaveTrackAtom(fileHandle, _Id, "tref.forc")) { + uint64_t forcedId = 0; + MP4GetTrackIntegerProperty(fileHandle, _Id, "tref.forc.entries.trackId", &forcedId); + _forcedTrackId = (MP4TrackId) forcedId; + } + } + } + + return self; +} + +- (instancetype)init +{ + if ((self = [super init])) { + _name = [self defaultName]; + _format = MP42SubtitleFormatTx3g; + _mediaType = MP42MediaTypeSubtitle; + } + + return self; +} + +- (BOOL)writeToFile:(MP4FileHandle)fileHandle error:(NSError **)outError +{ + if (!fileHandle || !_Id) { + if ( outError != NULL) { + *outError = MP42Error(@"Error: couldn't mux subtitle track", + nil, + 120); + return NO; + + } + } + + if ([_updatedProperty valueForKey:@"forced"] || !_muxed) { + if (_forcedTrack) + _forcedTrackId = _forcedTrack.Id; + + if (MP4HaveTrackAtom(fileHandle, _Id, "tref.forc") && (_forcedTrackId == 0)) { + MP4RemoveAllTrackReferences(fileHandle, "tref.forc", _Id); + } + else if (MP4HaveTrackAtom(fileHandle, _Id, "tref.forc") && (_forcedTrackId)) { + MP4SetTrackIntegerProperty(fileHandle, _Id, "tref.forc.entries.trackId", _forcedTrackId); + } + else if (_forcedTrackId) + MP4AddTrackReference(fileHandle, "tref.forc", _forcedTrackId, _Id); + } + + if (_isEdited && !_muxed) { + _muxed = YES; + + MP4GetTrackFloatProperty(fileHandle, _Id, "tkhd.width", &trackWidth); + MP4GetTrackFloatProperty(fileHandle, _Id, "tkhd.height", &trackHeight); + + uint8_t *val; + uint8_t nval[36]; + uint32_t *ptr32 = (uint32_t*) nval; + uint32_t size; + + MP4GetTrackBytesProperty(fileHandle ,_Id, "tkhd.matrix", &val, &size); + memcpy(nval, val, size); + offsetX = CFSwapInt32BigToHost(ptr32[6]) / 0x10000; + offsetY = CFSwapInt32BigToHost(ptr32[7]) / 0x10000; + free(val); + + [super writeToFile:fileHandle error:outError]; + + return _Id; + } + else + [super writeToFile:fileHandle error:outError]; + + if (![_format isEqualToString:MP42SubtitleFormatVobSub]) { + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.tx3g.defTextBoxBottom", trackHeight); + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.tx3g.defTextBoxRight", trackWidth); + + uint32_t displayFlags = 0; + if (_verticalPlacement) + displayFlags = 0x20000000; + if (_someSamplesAreForced) + displayFlags |= 0x40000000; + if (_allSamplesAreForced) + displayFlags |= 0x80000000; + + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.tx3g.displayFlags", displayFlags); + } + + return YES; +} + +@synthesize verticalPlacement = _verticalPlacement; + +- (BOOL)someSamplesAreForced { + return _someSamplesAreForced; +} + +- (void)setSomeSamplesAreForced:(BOOL)value +{ + _someSamplesAreForced = value; + _isEdited = YES; + + [_updatedProperty setValue:@"True" forKey:@"forcedSubtitles"]; +} + +- (BOOL)allSamplesAreForced { + return _allSamplesAreForced; +} + +- (void)setAllSamplesAreForced:(BOOL)value +{ + _allSamplesAreForced = value; + _isEdited = YES; + + [_updatedProperty setValue:@"True" forKey:@"forcedSubtitles"]; +} + +@synthesize forcedTrackId = _forcedTrackId; + +typedef struct style_record { + uint16_t startChar; + uint16_t endChar; + uint16_t fontID; + uint8_t fontStyles; + uint8_t fontSize; + rgba_color color; +} style_record; + +typedef struct tbox_record { + uint16_t top; + uint16_t left; + uint16_t bottom; + uint16_t right; +} tbox_record; + +static void insertTag(NSString* tag, NSMutableString *sampleText, NSUInteger *index, uint8_t *fontStyles, uint8_t type, uint8_t status) { + [sampleText insertString:tag atIndex:*index]; + *index += [tag length]; + + if (status == kTagOpen) + *fontStyles |= type; + else if (status == kTagClose) + *fontStyles ^= type; +} + +static void insertTagsFromStyleRecord(style_record record, NSMutableString *sampleText, uint8_t *fontStyles, rgba_color fontColor, uint8_t *numberOfInsertedChars) { + NSUInteger len = [sampleText length]; + NSUInteger index = record.startChar + *numberOfInsertedChars; + rgba_color dcolor = {0xFF, 0xFF, 0xFF, 0xFF}; + + if (record.startChar <= len && record.endChar <= len) { + // Open tag + if ((record.fontStyles & kStyleColor && !(*fontStyles & kStyleColor)) || + (compare_color(record.color, fontColor) && compare_color(record.color, dcolor))) { + // Special case: if there is already a font tag open, close it; + if (!(record.fontStyles & kStyleColor && !(*fontStyles & kStyleColor))) + insertTag(@"", sampleText, &index, fontStyles, 0, kTagClose); + + NSString *font = [NSString stringWithFormat:@"", (uint8_t)record.color.r, (uint8_t)record.color.g, (uint8_t)record.color.b]; + insertTag(font, sampleText, &index, fontStyles, kStyleColor, kTagOpen); + } + if (record.fontStyles & kStyleBold && !(*fontStyles & kStyleBold)) + insertTag(@"", sampleText, &index, fontStyles, kStyleBold, kTagOpen); + + if (record.fontStyles & kStyleItalic && !(*fontStyles & kStyleItalic)) + insertTag(@"", sampleText, &index, fontStyles, kStyleItalic, kTagOpen); + + if (record.fontStyles & kStyleUnderlined && !(*fontStyles & kStyleUnderlined)) + insertTag(@"", sampleText, &index, fontStyles, kStyleUnderlined, kTagOpen); + + // Close tag + if (!(record.fontStyles & kStyleUnderlined) && *fontStyles & kStyleUnderlined) + insertTag(@"", sampleText, &index, fontStyles, kStyleUnderlined, kTagClose); + + if (!(record.fontStyles & kStyleItalic) && *fontStyles & kStyleItalic) + insertTag(@"", sampleText, &index, fontStyles, kStyleItalic, kTagClose); + + if (!(record.fontStyles & kStyleBold) && *fontStyles & kStyleBold) + insertTag(@"", sampleText, &index, fontStyles, kStyleBold, kStyleColor); + + + if ((!(record.fontStyles & kStyleColor) && *fontStyles & kStyleColor)) + insertTag(@"", sampleText, &index, fontStyles, kStyleColor, kTagClose); + } + + *numberOfInsertedChars += index - record.startChar - *numberOfInsertedChars; +} + +- (BOOL)exportToURL:(NSURL *)url error:(NSError **)error +{ + MP4FileHandle fileHandle = MP4Read([[_sourceURL path] UTF8String]); + if (!fileHandle) + return NO; + + MP4TrackId srcTrackId = _Id; + + MP4SampleId sampleId = 1; + NSUInteger srtSampleNumber = 1; + + MP4Timestamp time = 0; + uint32_t timeScale = MP4GetTrackTimeScale(fileHandle, srcTrackId); + uint64_t samples = MP4GetTrackNumberOfSamples(fileHandle, srcTrackId); + + NSMutableString *srtFile = [[[NSMutableString alloc] init] autorelease]; + + uint64_t r, g, b, a; + MP4GetTrackIntegerProperty(fileHandle, srcTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorRed", &r); + MP4GetTrackIntegerProperty(fileHandle, srcTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorGreen", &g); + MP4GetTrackIntegerProperty(fileHandle, srcTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorBlue", &b); + MP4GetTrackIntegerProperty(fileHandle, srcTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorAlpha", &a); + rgba_color dcolor = {r, g, b, a}; + + for (sampleId = 1; sampleId <= samples; sampleId++) { + uint8_t *pBytes = NULL; + uint64_t pos = 0; + uint32_t numBytes = 0; + MP4Duration sampleDuration; + MP4Duration renderingOffset; + MP4Timestamp pStartTime; + bool isSyncSample; + BOOL forced = NO; + BOOL tbox = NO; + + if (!MP4ReadSample(fileHandle, + srcTrackId, + sampleId, + &pBytes, &numBytes, + &pStartTime, &sampleDuration, &renderingOffset, + &isSyncSample)) { + break; + } + + NSMutableString * sampleText = nil; + NSUInteger textSampleLength = ((pBytes[0] << 8) & 0xff00) + pBytes[1]; + + if (textSampleLength) { + sampleText = [[[NSMutableString alloc] initWithBytes:(pBytes + 2) + length:textSampleLength + encoding:NSUTF8StringEncoding] autorelease]; + } + + // Let's see if there is an atom after the text sample + pos = textSampleLength + 2; + + while (pos + 8 < numBytes && sampleText) { + uint8_t *styleAtoms = pBytes + pos; + size_t atomLength = ((styleAtoms[0] << 24) & 0xff000000) + ((styleAtoms[1] << 16) & 0xff0000) + ((styleAtoms[2] << 8) & 0xff00) + styleAtoms[3]; + + pos += atomLength; + + if (pos <= numBytes) { + // If we found a style atom, read it and insert html-like tags in the new file + if (styleAtoms[4] == 's' && styleAtoms[5] == 't' && styleAtoms[6] == 'y' && styleAtoms[7] == 'l') { + uint16_t styleCount = ((styleAtoms[8] << 8) & 0xff00) + styleAtoms[9]; + uint8_t *style_sample = styleAtoms + 10; + uint8_t numberOfInsertedChars = 0; + + uint8_t styles = 0; + uint64_t endChar = [sampleText length]; + style_record previousRecord = {0, 0, 0, 0, 0, dcolor}; + + while (styleCount) { + // Read the style record + style_record record; + record.startChar = (style_sample[0] << 8) & 0xff00; + record.startChar += style_sample[1]; + record.endChar = (style_sample[2] << 8) & 0xff00; + record.endChar += style_sample[3]; + record.fontID = (style_sample[4] << 8) & 0xff00; + record.fontID += style_sample[5]; + record.fontStyles = style_sample[6]; + record.fontSize = style_sample[7]; + record.color.r = style_sample[8]; + record.color.g = style_sample[9]; + record.color.b = style_sample[10]; + record.color.a = style_sample[11]; + + // Is the color different? + if (compare_color(record.color, dcolor)) + record.fontStyles |= kStyleColor; + + // Create a record to close the gap between two non-adiacent records + if (record.startChar > previousRecord.endChar + 1) { + style_record gapRecord = {previousRecord.endChar, record.startChar - 1, 0, 0, 0, dcolor}; + insertTagsFromStyleRecord(gapRecord, sampleText, &styles, previousRecord.color, &numberOfInsertedChars); + } + + insertTagsFromStyleRecord(record, sampleText, &styles, previousRecord.color, &numberOfInsertedChars); + + previousRecord = record; + styleCount--; + style_sample += 12; + } + + // Add a final record to close all the remainings open tags + if (previousRecord.endChar < endChar + 1) { + style_record gapRecord = {previousRecord.endChar, endChar, 0, 0, 0, dcolor}; + insertTagsFromStyleRecord(gapRecord, sampleText, &styles, previousRecord.color, &numberOfInsertedChars); + } + } + else if (styleAtoms[4] == 'f' && styleAtoms[5] == 'r' && styleAtoms[6] == 'c' && styleAtoms[7] == 'd') { + // Found a forced atom + forced = YES; + } + else if (styleAtoms[4] == 't' && styleAtoms[5] == 'b' && styleAtoms[6] == 'o' && styleAtoms[7] == 'x') { + // Found a tbox atom, if top == 0, the sub line is aligned at the top + uint8_t *tbox_atom = styleAtoms + 8; + + tbox_record record; + record.top = (tbox_atom[0] << 8) & 0xff00; + record.top += tbox_atom[1]; + record.left = (tbox_atom[2] << 8) & 0xff00; + record.left += tbox_atom[3]; + record.bottom = (tbox_atom[4] << 8) & 0xff00; + record.bottom += tbox_atom[5]; + record.right = (tbox_atom[6] << 8) & 0xff00; + record.right += tbox_atom[7]; + + if (record.top == 0) + tbox = YES; + } + } + } + + if (textSampleLength) { + if ([sampleText characterAtIndex:[sampleText length] - 1] == '\n') + [sampleText deleteCharactersInRange:NSMakeRange([sampleText length] - 1, 1)]; + + if (sampleText) { + [srtFile appendFormat:@"%lu\n%@ --> %@", (unsigned long)srtSampleNumber++, + SRTStringFromTime(time, timeScale, ','), SRTStringFromTime(time + sampleDuration, timeScale, ',')]; + if (tbox) + [srtFile appendString:@" X1:0"]; + if (forced) + [srtFile appendString:@" !!!"]; + [srtFile appendString:@"\n"]; + + [srtFile appendString:sampleText]; + [srtFile appendString:@"\n\n"]; + } + } + + time += sampleDuration; + free(pBytes); + } + + MP4Close(fileHandle, 0); + + return [srtFile writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:error]; +} + +- (void)setForcedTrack:(MP42Track *)newForcedTrack +{ + _forcedTrack = newForcedTrack; + _forcedTrackId = 0; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"forced"]; +} + +- (MP42Track *)forcedTrack +{ + return _forcedTrack; +} + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [super encodeWithCoder:coder]; + + [coder encodeInt:1 forKey:@"MP42SubtitleTrackVersion"]; + + [coder encodeBool:_verticalPlacement forKey:@"verticalPlacement"]; + [coder encodeBool:_someSamplesAreForced forKey:@"someSamplesAreForced"]; + [coder encodeBool:_allSamplesAreForced forKey:@"allSamplesAreForced"]; + + [coder encodeInt64:_forcedTrackId forKey:@"forcedTrackId"]; +} + +- (id)initWithCoder:(NSCoder *)decoder +{ + self = [super initWithCoder:decoder]; + + _verticalPlacement = [decoder decodeBoolForKey:@"verticalPlacement"]; + _someSamplesAreForced = [decoder decodeBoolForKey:@"someSamplesAreForced"]; + _allSamplesAreForced = [decoder decodeBoolForKey:@"allSamplesAreForced"]; + + _forcedTrackId = (MP4TrackId)[decoder decodeInt64ForKey:@"forcedTrackId"]; + + return self; +} + +- (NSString *)defaultName { + return MP42MediaTypeSubtitle; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@end diff --git a/MP42/MP42Track.h b/MP42/MP42Track.h new file mode 100644 index 0000000..082942b --- /dev/null +++ b/MP42/MP42Track.h @@ -0,0 +1,93 @@ +// +// MP42Track.h +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import +#import "MP42ConverterProtocol.h" +#import "MP42MediaFormat.h" + +@class MP42FileImporter; +@class MP42SampleBuffer; +@class MP42Fifo; + +typedef struct muxer_helper { + // Input helpers + MP42FileImporter *importer; + id demuxer_context; + + // Output helpers + id converter; + MP42Fifo *fifo; + + BOOL done; +} muxer_helper; + +@interface MP42Track : NSObject { + MP42TrackId _Id; + MP42TrackId _sourceId; + + NSURL *_sourceURL; + NSString *_format; + NSString *_sourceFormat; + NSString *_mediaType; + + NSString *_name; + NSString *_language; + + BOOL _enabled; + uint64_t _alternate_group; + int64_t _startOffset; + + BOOL _isEdited; + BOOL _muxed; + BOOL _needConversion; + + uint64_t _size; + uint32_t _timescale; + uint32_t _bitrate; + MP42Duration _duration; + + NSMutableDictionary *_updatedProperty; + muxer_helper *_helper; +} + +- (instancetype)initWithSourceURL:(NSURL *)URL trackID:(NSInteger)trackID fileHandle:(MP42FileHandle)fileHandle; + +- (BOOL)writeToFile:(MP42FileHandle)fileHandle error:(NSError **)outError; +- (MP42SampleBuffer *)copyNextSample; + +- (NSString *)timeString; +- (NSString *)formatSummary; + +@property(nonatomic, readwrite) MP42TrackId Id; +@property(nonatomic, readwrite) MP42TrackId sourceId; + +@property(nonatomic, readwrite, retain) NSURL *sourceURL; +@property(nonatomic, readwrite, retain) NSString *format; +@property(nonatomic, readwrite, retain) NSString *sourceFormat; +@property(nonatomic, readonly, retain) NSString *mediaType; + +@property(nonatomic, readwrite, retain) NSString *name; +@property(nonatomic, readwrite, retain) NSString *language; + +@property(nonatomic, readwrite) BOOL enabled; +@property(nonatomic, readwrite) uint64_t alternate_group; +@property(nonatomic, readwrite) int64_t startOffset; + +@property(nonatomic, readonly) uint32_t timescale; +@property(nonatomic, readonly) uint32_t bitrate; +@property(nonatomic, readwrite) MP42Duration duration; + +@property(nonatomic, readwrite) BOOL isEdited; +@property(nonatomic, readwrite) BOOL muxed; +@property(nonatomic, readwrite) BOOL needConversion; + +@property(nonatomic, readwrite) uint64_t dataLength; + +@property(nonatomic, readonly) muxer_helper *muxer_helper; + +@end diff --git a/MP42/MP42Track.m b/MP42/MP42Track.m new file mode 100644 index 0000000..122fcb4 --- /dev/null +++ b/MP42/MP42Track.m @@ -0,0 +1,380 @@ +// +// MP42Track.m +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import "MP42Track.h" +#import "MP42Utilities.h" +#import "MP42FileImporter.h" +#import "MP42Sample.h" +#import "MP42Fifo.h" +#import "SBLanguages.h" + +@implementation MP42Track + +- (instancetype)init +{ + if ((self = [super init])) { + _enabled = YES; + _updatedProperty = [[NSMutableDictionary alloc] init]; + _name = @"Unknown Track"; + } + return self; +} + +- (instancetype)initWithSourceURL:(NSURL *)URL trackID:(NSInteger)trackID fileHandle:(MP4FileHandle)fileHandle +{ + if ((self = [super init])) { + _sourceURL = [URL retain]; + _Id = (MP4TrackId)trackID; + _isEdited = NO; + _muxed = YES; + _updatedProperty = [[NSMutableDictionary alloc] init]; + + if (fileHandle) { + _format = [getHumanReadableTrackMediaDataName(fileHandle, _Id) retain]; + _name = [getTrackName(fileHandle, _Id) retain]; + _language = [getHumanReadableTrackLanguage(fileHandle, _Id) retain]; + _bitrate = MP4GetTrackBitRate(fileHandle, _Id); + _duration = MP4ConvertFromTrackDuration(fileHandle, _Id, + MP4GetTrackDuration(fileHandle, _Id), + MP4_MSECS_TIME_SCALE); + _timescale = MP4GetTrackTimeScale(fileHandle, _Id); + _startOffset = getTrackStartOffset(fileHandle, _Id); + + _size = getTrackSize(fileHandle, _Id); + + uint64_t temp; + MP4GetTrackIntegerProperty(fileHandle, _Id, "tkhd.flags", &temp); + if (temp & TRACK_ENABLED) _enabled = YES; + else _enabled = NO; + MP4GetTrackIntegerProperty(fileHandle, _Id, "tkhd.alternate_group", &_alternate_group); + } + } + + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone +{ + MP42Track *copy = [[[self class] alloc] init]; + + if (copy) { + copy->_Id = _Id; + copy->_sourceId = _sourceId; + + copy->_sourceURL = [_sourceURL retain]; + copy->_sourceFormat = [_sourceFormat retain]; + copy->_format = [_format retain]; + copy->_name = [_name retain]; + copy->_language = [_language retain]; + copy->_enabled = _enabled; + copy->_alternate_group = _alternate_group; + copy->_startOffset = _startOffset; + + copy->_size = _size; + + copy->_timescale = _timescale; + copy->_bitrate = _bitrate; + copy->_duration = _duration; + + [copy->_updatedProperty release]; + copy->_updatedProperty = [_updatedProperty mutableCopy]; + + if (_helper) { + copy->_helper = calloc(1, sizeof(muxer_helper)); + copy->_helper->importer = _helper->importer; + } + } + + return copy; +} + +- (BOOL)writeToFile:(MP4FileHandle)fileHandle error:(NSError **)outError +{ + BOOL success = YES; + if (!fileHandle || !_Id) { + if ( outError != NULL) { + *outError = MP42Error(@"Failed to modify track", + nil, + 120); + return NO; + + } + } + + if ([_updatedProperty valueForKey:@"name"] || !_muxed) { + if (![_name isEqualToString:@"Video Track"] && + ![_name isEqualToString:@"Sound Track"] && + ![_name isEqualToString:@"Subtitle Track"] && + ![_name isEqualToString:@"Text Track"] && + ![_name isEqualToString:@"Chapter Track"] && + ![_name isEqualToString:@"Closed Caption Track"] && + ![_name isEqualToString:@"Unknown Track"] && + _name != nil) { + const char *cString = [_name cStringUsingEncoding: NSMacOSRomanStringEncoding]; + if (cString) + if (!MP4SetTrackName(fileHandle, _Id, cString)) + NSLog(@"Unable to set the track name"); + } + else + MP4SetTrackName(fileHandle, _Id, "\0"); + } + if ([_updatedProperty valueForKey:@"alternate_group"] || !_muxed) + MP4SetTrackIntegerProperty(fileHandle, _Id, "tkhd.alternate_group", _alternate_group); + if ([_updatedProperty valueForKey:@"start_offset"]) + setTrackStartOffset(fileHandle, _Id, _startOffset); + if ([_updatedProperty valueForKey:@"language"] || !_muxed) + MP4SetTrackLanguage(fileHandle, _Id, lang_for_english([_language UTF8String])->iso639_2); + if ([_updatedProperty valueForKey:@"enabled"] || !_muxed) { + if (_enabled) MP4SetTrackEnabled(fileHandle, _Id); + else MP4SetTrackDisabled(fileHandle, _Id); + } + + return success; +} + +- (NSString *)timeString +{ + return SMPTEStringFromTime(_duration, 1000); +} + +@synthesize sourceURL = _sourceURL; +@synthesize Id = _Id; +@synthesize sourceId = _sourceId; + +@synthesize format = _format; +@synthesize sourceFormat = _sourceFormat; +@synthesize name = _name; + +- (NSString *)name { + return [[_name retain] autorelease]; +} + +- (NSString *)defaultName { + return @"Unknown Track"; +} + +- (void)setName:(NSString *)newName +{ + [_name autorelease]; + if ([newName length]) + _name = [newName retain]; + else + _name = [self defaultName]; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"name"]; +} + +- (NSString *)language { + return [[_language retain] autorelease]; +} + +- (void)setLanguage:(NSString *)newLang +{ + [_language autorelease]; + _language = [newLang retain]; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"language"]; +} + +- (BOOL)enabled { + return _enabled; +} + +- (void)setEnabled:(BOOL)newState +{ + _enabled = newState; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"enabled"]; +} + +- (uint64_t)alternate_group { + return _alternate_group; +} + +- (void)setAlternate_group:(uint64_t)newGroup +{ + _alternate_group = newGroup; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"alternate_group"]; +} + +- (int64_t)startOffset { + return _startOffset; +} + +- (void)setStartOffset:(int64_t)newOffset +{ + _startOffset = newOffset; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"start_offset"]; +} + +- (NSString *)formatSummary +{ + return [[_format retain] autorelease]; +} + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [coder encodeInt:2 forKey:@"MP42TrackVersion"]; + + [coder encodeInt64:_Id forKey:@"Id"]; + [coder encodeInt64:_sourceId forKey:@"sourceId"]; + +#ifdef SB_SANDBOX + if ([sourceURL respondsToSelector:@selector(startAccessingSecurityScopedResource)]) { + NSData *bookmarkData = nil; + NSError *error = nil; + bookmarkData = [sourceURL bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope + includingResourceValuesForKeys:nil + relativeToURL:nil // Make it app-scoped + error:&error]; + if (error) { + NSLog(@"Error creating bookmark for URL (%@): %@", sourceURL, error); + } + + [coder encodeObject:bookmarkData forKey:@"bookmark"]; + } + else { + [coder encodeObject:sourceURL forKey:@"sourceURL"]; + } +#else + [coder encodeObject:_sourceURL forKey:@"sourceURL"]; +#endif + + [coder encodeObject:_sourceFormat forKey:@"sourceFormat"]; + [coder encodeObject:_format forKey:@"format"]; + [coder encodeObject:_name forKey:@"name"]; + [coder encodeObject:_language forKey:@"language"]; + + [coder encodeBool:_enabled forKey:@"enabled"]; + + [coder encodeInt64:_alternate_group forKey:@"alternate_group"]; + [coder encodeInt64:_startOffset forKey:@"startOffset"]; + + [coder encodeBool:_isEdited forKey:@"isEdited"]; + [coder encodeBool:_muxed forKey:@"muxed"]; + [coder encodeBool:_needConversion forKey:@"needConversion"]; + + [coder encodeInt32:_timescale forKey:@"timescale"]; + [coder encodeInt32:_bitrate forKey:@"bitrate"]; + [coder encodeInt64:_duration forKey:@"duration"]; + + [coder encodeInt64:_size forKey:@"dataLength"]; + + [coder encodeObject:_updatedProperty forKey:@"updatedProperty"]; +} + +- (id)initWithCoder:(NSCoder *)decoder +{ + self = [super init]; + + NSInteger version = [decoder decodeInt32ForKey:@"MP42TrackVersion"]; + + _Id = (MP4TrackId)[decoder decodeInt64ForKey:@"Id"]; + _sourceId = (MP4TrackId)[decoder decodeInt64ForKey:@"sourceId"]; + + NSData *bookmarkData = [decoder decodeObjectForKey:@"bookmark"]; + if (bookmarkData) { + BOOL bookmarkDataIsStale; + NSError *error; + _sourceURL = [[NSURL + URLByResolvingBookmarkData:bookmarkData + options:NSURLBookmarkResolutionWithSecurityScope + relativeToURL:nil + bookmarkDataIsStale:&bookmarkDataIsStale + error:&error] retain]; + } + else { + _sourceURL = [[decoder decodeObjectForKey:@"sourceURL"] retain]; + } + + _sourceFormat = [[decoder decodeObjectForKey:@"sourceFormat"] retain]; + _format = [[decoder decodeObjectForKey:@"format"] retain]; + _name = [[decoder decodeObjectForKey:@"name"] retain]; + _language = [[decoder decodeObjectForKey:@"language"] retain]; + + _enabled = [decoder decodeBoolForKey:@"enabled"]; + + _alternate_group = [decoder decodeInt64ForKey:@"alternate_group"]; + _startOffset = [decoder decodeInt64ForKey:@"startOffset"]; + + _isEdited = [decoder decodeBoolForKey:@"isEdited"]; + _muxed = [decoder decodeBoolForKey:@"muxed"]; + _needConversion = [decoder decodeBoolForKey:@"needConversion"]; + + _timescale = [decoder decodeInt32ForKey:@"timescale"]; + _bitrate = [decoder decodeInt32ForKey:@"bitrate"]; + _duration = [decoder decodeInt64ForKey:@"duration"]; + + if (version == 2) + _size = [decoder decodeInt64ForKey:@"dataLength"]; + + _updatedProperty = [[decoder decodeObjectForKey:@"updatedProperty"] retain]; + + return self; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"Track: %d, %@, %@, %llu kbit/s, %@", [self Id], [self name], [self timeString], [self dataLength] / [self duration] * 8, [self format]]; +} + +@synthesize timescale = _timescale; +@synthesize bitrate = _bitrate; +@synthesize duration = _duration; +@synthesize isEdited = _isEdited; +@synthesize muxed = _muxed; +@synthesize needConversion = _needConversion; +@synthesize dataLength = _size; +@synthesize mediaType = _mediaType; + +@synthesize muxer_helper = _helper; + +- (muxer_helper *)muxer_helper +{ + if (_helper == NULL) + _helper = calloc(1, sizeof(muxer_helper)); + + return _helper; +} + +- (MP42SampleBuffer *)copyNextSample { + MP42SampleBuffer *sample = nil; + + if (_helper->converter) { + if ([_helper->importer done]) + [_helper->converter setInputDone]; + + if ([_helper->converter encoderDone]) + _helper->done = YES; + + sample = [_helper->converter copyEncodedSample]; + } else { + if ([_helper->fifo isEmpty] && [_helper->importer done]) + _helper->done = YES; + + if ([_helper->fifo count]) + sample = [_helper->fifo deque]; + } + + return sample; +} + +- (void)dealloc +{ + free(_helper); + + [_updatedProperty release]; + [_format release]; + [_sourceURL release]; + [_name release]; + [_language release]; + [super dealloc]; +} + +@end diff --git a/MP42/MP42Utilities.h b/MP42/MP42Utilities.h new file mode 100644 index 0000000..68b903c --- /dev/null +++ b/MP42/MP42Utilities.h @@ -0,0 +1,72 @@ +/* + * MP42Utilities.h + * Subler + * + * Created by Damiano Galassi on 30/01/09. + * Copyright 2009 Damiano Galassi. All rights reserved. + * + */ + +#import +#include "mp4v2.h" + +extern NSString * const SBMonoMixdown; +extern NSString * const SBStereoMixdown; +extern NSString * const SBDolbyMixdown; +extern NSString * const SBDolbyPlIIMixdown; + +typedef enum { TRACK_DISABLED = 0x0, + TRACK_ENABLED = 0x1, + TRACK_IN_MOVIE = 0x2, + TRACK_IN_PREVIEW = 0x4, + TRACK_IN_POSTER = 0x8 +} track_header_flags; + +NSString* SRTStringFromTime( long long time, long timeScale , const char separator); +NSString* SMPTEStringFromTime(long long time, long timeScale); +MP4Duration TimeFromSMPTEString( NSString* SMPTE_string, MP4Duration timeScale ); + +int MP4SetTrackEnabled(MP4FileHandle fileHandle, MP4TrackId trackId); +int MP4SetTrackDisabled(MP4FileHandle fileHandle, MP4TrackId trackId); + +int updateTracksCount(MP4FileHandle fileHandle); +void updateMoovDuration(MP4FileHandle fileHandle); + +uint64_t getTrackSize(MP4FileHandle fileHandle, MP4TrackId trackId); +int isHdVideo(uint64_t width, uint64_t height); + +MP4TrackId findChapterTrackId(MP4FileHandle fileHandle); +void removeAllChapterTrackReferences(MP4FileHandle fileHandle); +MP4TrackId findFirstVideoTrack(MP4FileHandle fileHandle); + +uint16_t getFixedVideoWidth(MP4FileHandle fileHandle, MP4TrackId videoTrack); + +NSString* getTrackName(MP4FileHandle fileHandle, MP4TrackId videoTrack); +NSString* getHumanReadableTrackMediaDataName(MP4FileHandle fileHandle, MP4TrackId videoTrack); +NSString* getHumanReadableTrackLanguage(MP4FileHandle fileHandle, MP4TrackId videoTrack); +NSString* getFilenameLanguage(CFStringRef filename); + +uint8_t *CreateEsdsFromSetupData(uint8_t *codecPrivate, size_t vosLen, size_t *esdsLen, int trackID, bool audio, bool write_version); +ComponentResult ReadESDSDescExt(void* descExt, UInt8 **buffer, int *size, int versionFlags); +CFDataRef createDescExt_XiphVorbis(UInt32 codecPrivateSize, const void * codecPrivate); +CFDataRef createDescExt_XiphFLAC(UInt32 codecPrivateSize, const void * codecPrivate); + +int readAC3Config(uint64_t acmod, uint64_t lfeon, UInt32 *channelsCount, UInt32 *channelLayoutTag); + +BOOL isTrackMuxable(NSString * formatName); +BOOL trackNeedConversion(NSString * formatName); + +NSArray *supportedFileFormat(); +BOOL isFileFormatSupported(NSString * fileExt); + +int64_t getTrackStartOffset(MP4FileHandle fileHandle, MP4TrackId Id); +void setTrackStartOffset(MP4FileHandle fileHandle, MP4TrackId Id, int64_t offset); +int copyTrackEditLists (MP4FileHandle fileHandle, MP4TrackId srcTrackId, MP4TrackId dstTrackId); + +NSError* MP42Error(NSString *description, NSString* recoverySuggestion, NSInteger code); +int yuv2rgb(int yuv); +int rgb2yuv(int rgb); + +void *fast_realloc_with_padding(void *ptr, unsigned int *size, unsigned int min_size); +int DecompressZlib(uint8_t **sampleData, uint32_t *sampleSize); +int DecompressBzlib(uint8_t **sampleData, uint32_t *sampleSize); diff --git a/MP42/MP42Utilities.m b/MP42/MP42Utilities.m new file mode 100644 index 0000000..2784f3b --- /dev/null +++ b/MP42/MP42Utilities.m @@ -0,0 +1,1079 @@ +/* + * MP42Utilities.c + * Subler + * + * Created by Damiano Galassi on 30/01/09. + * Copyright 2009 Damiano Galassi. All rights reserved. + * + */ + +#import "MP42Utilities.h" +#import +#import +#include +#include + +#import "SBLanguages.h" +#import "MP42MediaFormat.h" +#include "intreadwrite.h" +#include "avcodec.h" + +NSString* SRTStringFromTime( long long time, long timeScale , const char separator) +{ + NSString *SRT_string; + int hour, minute, second, msecond; + long long result; + + result = time / timeScale; // second + + msecond = (time % timeScale) / (timeScale / 1000.0f); + + second = result % 60; + + result = result / 60; // minute + minute = result % 60; + + result = result / 60; // hour + hour = result % 24; + + SRT_string = [NSString stringWithFormat:@"%02d:%02d:%02d%c%03d", hour, minute, second, separator, msecond]; // h:mm:ss:fff + + return SRT_string; +} + +NSString* SMPTEStringFromTime( long long time, long timeScale ) +{ + NSString *SMPTE_string; + int hour, minute, second, frame; + long long result; + + result = time / timeScale; // second + frame = (time % timeScale) / 10; + + second = result % 60; + + result = result / 60; // minute + minute = result % 60; + + result = result / 60; // hour + hour = result % 24; + + SMPTE_string = [NSString stringWithFormat:@"%d:%02d:%02d:%02d", hour, minute, second, frame]; // h:mm:ss:ff + + return SMPTE_string; +} + +MP4Duration TimeFromSMPTEString( NSString* SMPTE_string, MP4Duration timeScale ) +{ + int hour, minute, second, frame; + MP4Duration timeval; + + sscanf([SMPTE_string UTF8String], "%d:%02d:%02d:%02d",&hour, &minute, &second, &frame); + + timeval = hour * 60 * 60 + minute * 60 + second; + timeval = timeScale * timeval + ( frame * 10 ); + + return timeval; +} + + +int MP4SetTrackEnabled(MP4FileHandle fileHandle, MP4TrackId trackId) +{ + return MP4SetTrackIntegerProperty(fileHandle, trackId, "tkhd.flags", (TRACK_ENABLED | TRACK_IN_MOVIE)); +} + +int MP4SetTrackDisabled(MP4FileHandle fileHandle, MP4TrackId trackId) +{ + return MP4SetTrackIntegerProperty(fileHandle, trackId, "tkhd.flags", (TRACK_DISABLED | TRACK_IN_MOVIE)); +} + +int updateTracksCount(MP4FileHandle fileHandle) +{ + MP4TrackId maxTrackId = 0; + unsigned int i; + for (i = 0; i< MP4GetNumberOfTracks( fileHandle, 0, 0); i++ ) + if (MP4FindTrackId(fileHandle, i, 0, 0) > maxTrackId) + maxTrackId = MP4FindTrackId(fileHandle, i, 0, 0); + + return MP4SetIntegerProperty(fileHandle, "moov.mvhd.nextTrackId", maxTrackId + 1); +} + +void updateMoovDuration(MP4FileHandle fileHandle) +{ + MP4TrackId trackId = 0; + MP4Duration maxTrackDuration = 0, trackDuration = 0; + unsigned int i; + for (i = 0; i< MP4GetNumberOfTracks( fileHandle, 0, 0); i++ ) { + trackId = MP4FindTrackId(fileHandle, i, 0, 0); + MP4GetTrackIntegerProperty(fileHandle, trackId, "tkhd.duration", &trackDuration); + if (maxTrackDuration < trackDuration) + maxTrackDuration = trackDuration; + } + MP4SetIntegerProperty(fileHandle, "moov.mvhd.duration", maxTrackDuration); +} + +uint64_t getTrackSize(MP4FileHandle fileHandle, MP4TrackId trackId) +{ + uint64_t i, sampleNum, dataLength; + i = 1; + sampleNum = MP4GetTrackNumberOfSamples(fileHandle, trackId); + dataLength = 0; + + while (i <= sampleNum) { + dataLength += MP4GetSampleSize(fileHandle, trackId, i); + i++; + } + + return dataLength; +} + +int isHdVideo(uint64_t width, uint64_t height) +{ + if ((width > 1280) || (height > 720)) + return 2; + else if (((width >= 960) && (height >= 720)) || width >= 1280) + return 1; + + return 0; +} + +MP4TrackId findChapterTrackId(MP4FileHandle fileHandle) +{ + MP4TrackId trackId = 0; + uint64_t trackRef; + unsigned int i; + for (i = 0; i< MP4GetNumberOfTracks( fileHandle, 0, 0); i++ ) { + trackId = MP4FindTrackId(fileHandle, i, 0, 0); + if (MP4HaveTrackAtom(fileHandle, trackId, "tref.chap")) { + MP4GetTrackIntegerProperty(fileHandle, trackId, "tref.chap.entries.trackId", &trackRef); + if (trackRef > 0) + return (MP4TrackId) trackRef; + } + } + return 0; +} + +void removeAllChapterTrackReferences(MP4FileHandle fileHandle) +{ + MP4TrackId trackId = 0; + unsigned int i; + for (i = 0; i< MP4GetNumberOfTracks( fileHandle, 0, 0); i++ ) { + trackId = MP4FindTrackId(fileHandle, i, 0, 0); + if (MP4HaveTrackAtom(fileHandle, trackId, "tref.chap")) { + MP4RemoveAllTrackReferences(fileHandle, "tref.chap", trackId); + } + } + return; +} + +MP4TrackId findFirstVideoTrack(MP4FileHandle fileHandle) +{ + MP4TrackId videoTrack = 0; + int i, trackNumber = MP4GetNumberOfTracks( fileHandle, 0, 0); + if (!trackNumber) + return 0; + for (i = 0; i < trackNumber; i++) { + videoTrack = MP4FindTrackId(fileHandle, i, 0, 0); + const char *trackType = MP4GetTrackType(fileHandle, videoTrack); + if (trackType) + if (!strcmp(trackType, MP4_VIDEO_TRACK_TYPE)) + return videoTrack; + } + return 0; +} + +uint16_t getFixedVideoWidth(MP4FileHandle fileHandle, MP4TrackId Id) +{ + uint16_t videoWidth = MP4GetTrackVideoWidth(fileHandle, Id); + + if (MP4HaveTrackAtom(fileHandle, Id, "mdia.minf.stbl.stsd.*.pasp")) { + uint64_t hSpacing, vSpacing; + MP4GetTrackIntegerProperty(fileHandle, Id, "mdia.minf.stbl.stsd.*.pasp.hSpacing", &hSpacing); + MP4GetTrackIntegerProperty(fileHandle, Id, "mdia.minf.stbl.stsd.*.pasp.vSpacing", &vSpacing); + if( hSpacing > 0 && vSpacing > 0) + return (uint16_t) (videoWidth / (float) vSpacing * (float) hSpacing); + else + return videoWidth; + } + + return videoWidth; +} + +NSString* getTrackName(MP4FileHandle fileHandle, MP4TrackId Id) +{ + char *trackName; + + if (MP4GetTrackName(fileHandle, Id, &trackName)) { + NSString * name = [NSString stringWithCString:trackName encoding: NSMacOSRomanStringEncoding]; + free(trackName); + return name; + } + + const char* type = MP4GetTrackType(fileHandle, Id); + if (!strcmp(type, MP4_AUDIO_TRACK_TYPE)) + return NSLocalizedString(@"Sound Track", @"Sound Track"); + else if (!strcmp(type, MP4_VIDEO_TRACK_TYPE)) + return NSLocalizedString(@"Video Track", @"Video Track"); + else if (!strcmp(type, MP4_TEXT_TRACK_TYPE)) + return NSLocalizedString(@"Text Track", @"Text Track"); + else if (!strcmp(type, MP4_SUBTITLE_TRACK_TYPE)) + return NSLocalizedString(@"Subtitle Track", @"Subtitle Track"); + else if (!strcmp(type, "clcp")) + return NSLocalizedString(@"Closed Caption Track", @"Closed Caption Track"); + else if (!strcmp(type, MP4_OD_TRACK_TYPE)) + return NSLocalizedString(@"MPEG-4 ODSM Track", @"MPEG-4 ODSM Track"); + else if (!strcmp(type, MP4_SCENE_TRACK_TYPE)) + return NSLocalizedString(@"MPEG-4 SDSM Track", @"MPEG-4 SDSM Track"); + else if (!strcmp(type, "tmcd")) + return NSLocalizedString(@"Timecode Track", @"Timecode Track"); + else if (!strcmp(type, "subp")) + return NSLocalizedString(@"Subtitle Track", @"Subtitle Track"); + else + return NSLocalizedString(@"Unknown Track", @"Unknown Track"); +} + +NSString* getHumanReadableTrackMediaDataName(MP4FileHandle fileHandle, MP4TrackId Id) +{ + const char* type = MP4GetTrackType(fileHandle, Id); + const char* dataName = MP4GetTrackMediaDataName(fileHandle, Id); + if (dataName) { + if (!strcmp(dataName, "avc1")) + return MP42VideoFormatH264; + else if (!strcmp(dataName, "mp4a")) { + uint8_t audiotype = MP4GetTrackEsdsObjectTypeId(fileHandle, Id); + if (audiotype == MP4_MPEG4_AUDIO_TYPE) + return MP42AudioFormatAAC; + else if (audiotype == MP4_MPEG2_AUDIO_TYPE) + return MP42AudioFormatMP3; + else if (audiotype == 0xA9) + return MP42AudioFormatDTS; + } + else if (!strcmp(dataName, "alac")) + return MP42AudioFormatALAC; + else if (!strcmp(dataName, "ac-3")) + return MP42AudioFormatAC3; + else if (!strcmp(dataName, "mp4v")) + return MP42VideoFormatMPEG4Visual; + else if (!strcmp(dataName, "text")) + return MP42SubtitleFormatText; + else if (!strcmp(dataName, "tx3g")) + return MP42SubtitleFormatTx3g; + else if (!strcmp(dataName, "c608")) + return MP42ClosedCaptionFormatCEA608; + else if (!strcmp(dataName, "c708")) + return MP42ClosedCaptionFormatCEA708; + else if (!strcmp(dataName, "samr")) + return MP42AudioFormatAMR; + else if (!strcmp(dataName, "jpeg")) + return MP42VideoFormatJPEG; + else if (!strcmp(dataName, "rtp ")) + return @"Hint"; + else if (!strcmp(dataName, "drms")) + return MP42AudioFormatFairPlay; + else if (!strcmp(dataName, "drmi")) + return MP42VideoFormatFairPlay; + else if (!strcmp(dataName, "tmcd")) + return MP42TimeCodeFormat; + else if (!strcmp(dataName, "mp4s") && !strcmp(type, "subp")) + return MP42SubtitleFormatVobSub; + + else + return [NSString stringWithUTF8String:dataName]; + } + + return @"Unknown"; +} + +NSString* getHumanReadableTrackLanguage(MP4FileHandle fileHandle, MP4TrackId Id) +{ + NSString *language; + char lang[4] = ""; + MP4GetTrackLanguage(fileHandle, Id, lang); + language = [NSString stringWithFormat:@"%s", lang_for_code2(lang)->eng_name]; + + return language; +} + +// if the subtitle filename is something like title.en.srt or movie.fre.srt +// this function detects it and returns the subtitle language +NSString* getFilenameLanguage(CFStringRef filename) +{ + CFRange findResult; + CFStringRef baseName = NULL; + CFStringRef langStr = NULL; + NSString *lang = @"English"; + + // find and strip the extension + findResult = CFStringFind(filename, CFSTR("."), kCFCompareBackwards); + findResult.length = findResult.location; + findResult.location = 0; + baseName = CFStringCreateWithSubstring(NULL, filename, findResult); + + // then find the previous period + findResult = CFStringFind(baseName, CFSTR("."), kCFCompareBackwards); + findResult.location++; + findResult.length = CFStringGetLength(baseName) - findResult.location; + + // check for 3 char language code + if (findResult.length == 3) { + char langCStr[4] = ""; + + langStr = CFStringCreateWithSubstring(NULL, baseName, findResult); + CFStringGetCString(langStr, langCStr, 4, kCFStringEncodingASCII); + lang = [NSString stringWithFormat:@"%s", lang_for_code2(langCStr)->eng_name]; + + CFRelease(langStr); + + // and for a 2 char language code + } else if (findResult.length == 2) { + char langCStr[3] = ""; + + langStr = CFStringCreateWithSubstring(NULL, baseName, findResult); + CFStringGetCString(langStr, langCStr, 3, kCFStringEncodingASCII); + lang = [NSString stringWithFormat:@"%s", lang_for_code_s(langCStr)->eng_name]; + + CFRelease(langStr); + } + else if (findResult.length) { + char langCStr[40] = ""; + + langStr = CFStringCreateWithSubstring(NULL, baseName, findResult); + CFStringGetCString(langStr, langCStr, 40, kCFStringEncodingASCII); + lang = [NSString stringWithFormat:@"%s", lang_for_english(langCStr)->eng_name]; + + CFRelease(langStr); + } + + CFRelease(baseName); + return lang; +} + +/* write the data to the target adress & then return a pointer which points after the written data */ +uint8_t *write_data(uint8_t *target, uint8_t* data, int32_t data_size) +{ + if(data_size > 0) + memcpy(target, data, data_size); + return (target + data_size); +} /* write_data() */ + +/* write the int32_t data to target & then return a pointer which points after that data */ +uint8_t *write_int32(uint8_t *target, int32_t data) +{ + return write_data(target, (uint8_t*)&data, sizeof(data)); +} /* write_int32() */ + +/* write the int16_t data to target & then return a pointer which points after that data */ +uint8_t *write_int16(uint8_t *target, int16_t data) +{ + return write_data(target, (uint8_t*)&data, sizeof(data)); +} /* write_int16() */ + +#define MP4ESDescrTag 0x03 +#define MP4DecConfigDescrTag 0x04 +#define MP4DecSpecificDescrTag 0x05 + +// from perian +// based off of mov_mp4_read_descr_len from mov.c in ffmpeg's libavformat +static int readDescrLen(UInt8 **buffer) +{ + int len = 0; + int count = 4; + while (count--) { + int c = *(*buffer)++; + len = (len << 7) | (c & 0x7f); + if (!(c & 0x80)) + break; + } + return len; +} + +// based off of mov_mp4_read_descr from mov.c in ffmpeg's libavformat +static int readDescr(UInt8 **buffer, int *tag) +{ + *tag = *(*buffer)++; + return readDescrLen(buffer); +} + +// based off of mov_read_esds from mov.c in ffmpeg's libavformat +ComponentResult ReadESDSDescExt(void* descExt, UInt8 **buffer, int *size, int versionFlags) +{ + UInt8 *esds = (UInt8 *) descExt; + int tag, len; + *size = 0; + + if (versionFlags) + esds += 4; // version + flags + readDescr(&esds, &tag); + esds += 2; // ID + if (tag == MP4ESDescrTag) + esds++; // priority + + readDescr(&esds, &tag); + if (tag == MP4DecConfigDescrTag) { + esds++; // object type id + esds++; // stream type + esds += 3; // buffer size db + esds += 4; // max bitrate + esds += 4; // average bitrate + + len = readDescr(&esds, &tag); + if (tag == MP4DecSpecificDescrTag) { + *buffer = calloc(1, len + 8); + if (*buffer) { + memcpy(*buffer, esds, len); + *size = len; + } + } + } + + return noErr; +} + +// the esds atom creation is based off of the routines for it in ffmpeg's movenc.c +static unsigned int descrLength(unsigned int len) +{ + int i; + for(i=1; len>>(7*i); i++); + return len + 1 + i; +} + +static uint8_t* putDescr(uint8_t *buffer, int tag, unsigned int size) +{ + int i= descrLength(size) - size - 2; + *buffer++ = tag; + for(; i>0; i--) + *buffer++ = (size>>(7*i)) | 0x80; + *buffer++ = size & 0x7F; + return buffer; +} + +// ESDS layout: +// + version (4 bytes) +// + ES descriptor +// + Track ID (2 bytes) +// + Flags (1 byte) +// + DecoderConfig descriptor +// + Object Type (1 byte) +// + Stream Type (1 byte) +// + Buffersize DB (3 bytes) +// + Max bitrate (4 bytes) +// + VBR/Avg bitrate (4 bytes) +// + DecoderSpecific info descriptor +// + codecPrivate (codecPrivate->GetSize()) +// + SL descriptor +// + dunno (1 byte) + +uint8_t *CreateEsdsFromSetupData(uint8_t *codecPrivate, size_t vosLen, size_t *esdsLen, int trackID, bool audio, bool write_version) +{ + int decoderSpecificInfoLen = vosLen ? descrLength(vosLen) : 0; + int versionLen = write_version ? 4 : 0; + + *esdsLen = versionLen + descrLength(3 + descrLength(13 + decoderSpecificInfoLen) + descrLength(1)); + uint8_t *esds = (uint8_t*)malloc(*esdsLen); + UInt8 *pos = (UInt8 *) esds; + + // esds atom version (only needed for ImageDescription extension) + if (write_version) + pos = write_int32(pos, 0); + + // ES Descriptor + pos = putDescr(pos, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) + descrLength(1)); + pos = write_int16(pos, EndianS16_NtoB(trackID)); + *pos++ = 0; // no flags + + // DecoderConfig descriptor + pos = putDescr(pos, 0x04, 13 + decoderSpecificInfoLen); + + // Object type indication, see http://gpac.sourceforge.net/tutorial/mediatypes.htm + if (audio) + *pos++ = 0x40; // aac + else + *pos++ = 0x20; // mpeg4 part 2 + + // streamtype + if (audio) + *pos++ = 0x15; + else + *pos++ = 0x11; + + // 3 bytes: buffersize DB (not sure how to get easily) + *pos++ = 0; + pos = write_int16(pos, 0); + + // max bitrate, not sure how to get easily + pos = write_int32(pos, 0); + + // vbr + pos = write_int32(pos, 0); + + if (vosLen) { + pos = putDescr(pos, 0x05, vosLen); + pos = write_data(pos, codecPrivate, vosLen); + } + + // SL descriptor + pos = putDescr(pos, 0x06, 1); + *pos++ = 0x02; + + return esds; +} + +enum { + // these are atoms/extension types defined by XiphQT for their codecs + kCookieTypeOggSerialNo = 'oCtN', + + kCookieTypeVorbisHeader = 'vCtH', + kCookieTypeVorbisComments = 'vCt#', + kCookieTypeVorbisCodebooks = 'vCtC', + kCookieTypeVorbisFirstPageNo = 'vCtN', + + kCookieTypeSpeexHeader = 'sCtH', + kCookieTypeSpeexComments = 'sCt#', + kCookieTypeSpeexExtraHeader = 'sCtX', + + kCookieTypeFLACStreaminfo = 'fCtS', + kCookieTypeFLACMetadata = 'fCtM', +}; + +// xiph-qt expects these this sound extension to have been created from first 3 packets +// which are stored in CodecPrivate in Matroska +CFDataRef createDescExt_XiphVorbis(UInt32 codecPrivateSize, const void * codecPrivate) +{ + if (codecPrivateSize) { + CFMutableDataRef sndDescExt = CFDataCreateMutable(NULL, 0); + + unsigned char *privateBuf; + size_t privateSize; + uint8_t numPackets; + int offset = 1, i; + UInt32 uid = 0; + + privateSize = codecPrivateSize; + privateBuf = (unsigned char *) codecPrivate; + numPackets = privateBuf[0] + 1; + + int packetSizes[numPackets]; + memset(packetSizes, 0, sizeof(packetSizes)); + + // get the sizes of the packets + packetSizes[numPackets - 1] = privateSize - 1; + int packetNum = 0; + for (i = 1; packetNum < numPackets - 1; i++) { + packetSizes[packetNum] += privateBuf[i]; + if (privateBuf[i] < 255) { + packetSizes[numPackets - 1] -= packetSizes[packetNum]; + packetNum++; + } + offset++; + } + packetSizes[numPackets - 1] -= offset - 1; + + if (offset+packetSizes[0]+packetSizes[1]+packetSizes[2] > privateSize) { + CFRelease(sndDescExt); + return NULL; + } + + // first packet + uint32_t serial_header_atoms[3+2] = { EndianU32_NtoB(3*4), + EndianU32_NtoB(kCookieTypeOggSerialNo), + EndianU32_NtoB(uid), + EndianU32_NtoB(packetSizes[0] + 2*4), + EndianU32_NtoB(kCookieTypeVorbisHeader) }; + + CFDataAppendBytes(sndDescExt, (UInt8 *)serial_header_atoms, sizeof(serial_header_atoms)); + CFDataAppendBytes(sndDescExt, &privateBuf[offset], packetSizes[0]); + + // second packet + uint32_t atomhead2[2] = { EndianU32_NtoB(packetSizes[1] + sizeof(atomhead2)), + EndianU32_NtoB(kCookieTypeVorbisComments) }; + CFDataAppendBytes(sndDescExt, (UInt8 *)atomhead2, sizeof(atomhead2)); + CFDataAppendBytes(sndDescExt, &privateBuf[offset + packetSizes[0]], packetSizes[1]); + + // third packet + uint32_t atomhead3[2] = { EndianU32_NtoB(packetSizes[2] + sizeof(atomhead3)), + EndianU32_NtoB(kCookieTypeVorbisCodebooks) }; + CFDataAppendBytes(sndDescExt, (UInt8 *)atomhead3, sizeof(atomhead3)); + CFDataAppendBytes(sndDescExt, &privateBuf[offset + packetSizes[1] + packetSizes[0]], packetSizes[2]); + + return sndDescExt; + } + return NULL; +} + +// xiph-qt expects these this sound extension to have been created in this way +// from the packets which are stored in the CodecPrivate element in Matroska +CFDataRef createDescExt_XiphFLAC(UInt32 codecPrivateSize, const void * codecPrivate) +{ + if (codecPrivateSize) { + CFMutableDataRef sndDescExt = CFDataCreateMutable(NULL, 0); + UInt32 uid = 0; + + size_t privateSize = codecPrivateSize; + UInt8 *privateBuf = (unsigned char *) codecPrivate, *privateEnd = privateBuf + privateSize; + + unsigned long serialnoatom[3] = { EndianU32_NtoB(sizeof(serialnoatom)), + EndianU32_NtoB(kCookieTypeOggSerialNo), + EndianU32_NtoB(uid) }; + + CFDataAppendBytes(sndDescExt, (UInt8 *)serialnoatom, sizeof(serialnoatom)); + + privateBuf += 4; // skip 'fLaC' + + while ((privateEnd - privateBuf) > 4) { + uint32_t packetHeader = EndianU32_BtoN(*(uint32_t*)privateBuf); + int lastPacket = packetHeader >> 31, blockType = (packetHeader >> 24) & 0x7F; + uint32_t packetSize = (packetHeader & 0xFFFFFF) + 4; + uint32_t xiphHeader[2] = {EndianU32_NtoB(packetSize + sizeof(xiphHeader)), + EndianU32_NtoB(blockType ? kCookieTypeFLACMetadata : kCookieTypeFLACStreaminfo)}; + + if ((privateEnd - privateBuf) < packetSize) + break; + + CFDataAppendBytes(sndDescExt, (UInt8 *)xiphHeader, sizeof(xiphHeader)); + CFDataAppendBytes(sndDescExt, privateBuf, packetSize); + + privateBuf += packetSize; + + if (lastPacket) + break; + } + + return sndDescExt; + } + return nil; +} + +static const int ac3_layout_no_lfe[8] = { + kAudioChannelLayoutTag_Stereo, + kAudioChannelLayoutTag_Mono, + kAudioChannelLayoutTag_Stereo, + kAudioChannelLayoutTag_ITU_3_0, + kAudioChannelLayoutTag_ITU_2_1, + kAudioChannelLayoutTag_ITU_3_1, + kAudioChannelLayoutTag_ITU_2_2, + kAudioChannelLayoutTag_ITU_3_2}; + +static const int ac3_layout_lfe[8] = { + kAudioChannelLayoutTag_DVD_4, + kAudioChannelLayoutTag_AC3_1_0_1, + kAudioChannelLayoutTag_DVD_4, + kAudioChannelLayoutTag_DVD_10, + kAudioChannelLayoutTag_DVD_5, + kAudioChannelLayoutTag_DVD_11, + kAudioChannelLayoutTag_DVD_6, + kAudioChannelLayoutTag_ITU_3_2_1}; + +int readAC3Config(uint64_t acmod, uint64_t lfeon, UInt32 *channelsCount, UInt32 *channelLayoutTag) +{ + if(lfeon) + *channelLayoutTag = ac3_layout_lfe[acmod]; + else + *channelLayoutTag = ac3_layout_no_lfe[acmod]; + + *channelsCount = AudioChannelLayoutTag_GetNumberOfChannels(*channelLayoutTag); + + return 1; +} + +BOOL isTrackMuxable(NSString * formatName) +{ + NSArray* supportedFormats = [NSArray arrayWithObjects:MP42VideoFormatH264, MP42VideoFormatMPEG4Visual, MP42AudioFormatAAC, MP42AudioFormatALAC, MP42AudioFormatAC3, MP42AudioFormatDTS, MP42SubtitleFormatTx3g, MP42SubtitleFormatText, MP42ClosedCaptionFormatCEA608, MP42VideoFormatJPEG, MP42SubtitleFormatVobSub, nil]; + + for (NSString* type in supportedFormats) + if ([formatName isEqualToString:type]) + return YES; + + return NO; +} + +BOOL trackNeedConversion(NSString * formatName) { + NSArray* supportedConversionFormats = [NSArray arrayWithObjects:MP42AudioFormatVorbis, MP42AudioFormatFLAC, MP42AudioFormatMP3, MP42AudioFormatTrueHD, MP42SubtitleFormatSSA, MP42SubtitleFormatText, MP42SubtitleFormatPGS, nil]; + + for (NSString* type in supportedConversionFormats) + if ([formatName isEqualToString:type]) + return YES; + + return NO; +} + +NSArray *supportedFileFormat() +{ + return [NSArray arrayWithObjects:@"scc", @"smi", @"txt", @"m4v", @"mp4", @"m4a", @"m4a", @"mov", @"mts", @"m2ts", + @"mkv", @"mka", @"mks", @"h264", @"264", @"idx", @"aac", @"ac3", @"srt", nil]; +} + +BOOL isFileFormatSupported(NSString * fileExt) { + NSArray *supportedFormat = supportedFileFormat(); + + for (NSString *type in supportedFormat) + if ([fileExt caseInsensitiveCompare:type] == NSOrderedSame) + return YES; + + return NO; +} + +int64_t getTrackStartOffset(MP4FileHandle fileHandle, MP4TrackId Id) +{ + int64_t offset = 0; + uint32_t i = 1, trackEditCount = MP4GetTrackNumberOfEdits(fileHandle, Id); + + while (i <= trackEditCount) { + MP4Duration editDuration = MP4GetTrackEditDuration(fileHandle, Id, i); + MP4Timestamp editMediaTime = MP4GetTrackEditMediaStart(fileHandle, Id, i); + //int8_t editMediaRate = MP4GetTrackEditDwell(fileHandle, Id, i); + + uint64_t editListVersion = 0; + MP4GetTrackIntegerProperty(fileHandle, Id, "edts.elst.version", &editListVersion); + + if (editListVersion == 0 && editMediaTime == ((uint32_t)-1)) + offset += MP4ConvertFromMovieDuration(fileHandle, editDuration, MP4_MILLISECONDS_TIME_SCALE); + else if (editListVersion == 1 && editMediaTime == ((uint64_t)-1)) + offset += MP4ConvertFromMovieDuration(fileHandle, editDuration, MP4_MILLISECONDS_TIME_SCALE); + else if (i == 1) + offset -= MP4ConvertFromTrackDuration(fileHandle, Id, editMediaTime, MP4_MILLISECONDS_TIME_SCALE); + + //NSLog(@"Track %d, Media Time = %lld, Segment Duration: %qu Media Rate:%d", Id, editMediaTime, editDuration, editMediaRate); + i++; + } + + //NSLog(@"Track %d offset: %d ms", Id, offset); + + return offset; +} + +MP4Duration getTrackDuration(MP4FileHandle fileHandle, MP4TrackId trackId) +{ + uint32_t trackEditsCount = MP4GetTrackNumberOfEdits(fileHandle, trackId); + MP4Duration duration = 0; + int i = 1; + + while( i <= trackEditsCount) { + duration += MP4GetTrackEditDuration(fileHandle, trackId, i); + i++; + } + + if (duration == 0) + duration = MP4ConvertFromTrackDuration(fileHandle, trackId, + MP4GetTrackDuration(fileHandle, trackId), + MP4GetTimeScale(fileHandle)); + + return duration; +} + +void setTrackStartOffset(MP4FileHandle fileHandle, MP4TrackId Id, int64_t offset) +{ + uint32_t trackEditsCount = MP4GetTrackNumberOfEdits(fileHandle, Id); + if (offset > 0) + offset = MP4ConvertToTrackDuration(fileHandle, Id, offset, MP4_MILLISECONDS_TIME_SCALE); + else + offset = -(MP4ConvertToTrackDuration(fileHandle, Id, -offset, MP4_MILLISECONDS_TIME_SCALE)); + + // If there is no existing edit list, just add some new ones at the start and do the usual stuff. + if (offset && !trackEditsCount) { + MP4Duration editDuration = MP4ConvertFromTrackDuration(fileHandle, + Id, + MP4GetTrackDuration(fileHandle, Id), + MP4GetTimeScale(fileHandle)); + if (offset > 0) { + MP4Duration delayDuration = MP4ConvertFromTrackDuration(fileHandle, + Id, + offset, + MP4GetTimeScale(fileHandle)); + + MP4AddTrackEdit(fileHandle, Id, MP4_INVALID_EDIT_ID, -1, delayDuration, 0); + MP4AddTrackEdit(fileHandle, Id, MP4_INVALID_EDIT_ID, 0, editDuration, 0); + } + else if (offset < 0) { + MP4Duration delayDuration = MP4ConvertFromTrackDuration(fileHandle, + Id, + -offset, + MP4GetTimeScale(fileHandle)); + + MP4AddTrackEdit(fileHandle, Id, MP4_INVALID_EDIT_ID, -offset, editDuration - delayDuration, 0); + } + } + // If the mp4 contains already some edits list, try to reuse them + else if (trackEditsCount) { + if (offset >= 0) { + // Remove all the empty edit lists + while (MP4GetTrackNumberOfEdits(fileHandle, Id)) { + uint64_t editListVersion = 0; + MP4Timestamp editMediaTime = MP4GetTrackEditMediaStart(fileHandle, Id, 1); + + MP4GetTrackIntegerProperty(fileHandle, Id, "edts.elst.version", &editListVersion); + + if (editListVersion == 0 && editMediaTime == ((uint32_t)-1)) + MP4DeleteTrackEdit(fileHandle, Id, 1); + else if (editListVersion == 1 && editMediaTime == ((uint64_t)-1)) + MP4DeleteTrackEdit(fileHandle, Id, 1); + else { + if (getTrackStartOffset(fileHandle, Id) < 0) { + MP4Duration oldEditDuration = MP4GetTrackEditDuration(fileHandle, Id, 1); + MP4Duration oldEditMediaStart = MP4GetTrackEditMediaStart(fileHandle, Id, 1); + oldEditMediaStart = MP4ConvertFromTrackDuration(fileHandle, + Id, + oldEditMediaStart, + MP4GetTimeScale(fileHandle)); + MP4SetTrackEditDuration(fileHandle, Id, 1, oldEditDuration + oldEditMediaStart); + MP4SetTrackEditMediaStart(fileHandle, Id, 1, 0); + + } + break; + } + } + + MP4Duration delayDuration = MP4ConvertFromTrackDuration(fileHandle, + Id, + offset, + MP4GetTimeScale(fileHandle)); + + if (offset != 0) + MP4AddTrackEdit(fileHandle, Id, 1, -1, delayDuration, 0); + } + else if (offset < 0) { + // First remove all the empty edit lists + while (MP4GetTrackNumberOfEdits(fileHandle, Id)) { + uint64_t editListVersion = 0; + MP4Timestamp editMediaTime = MP4GetTrackEditMediaStart(fileHandle, Id, 1); + + MP4GetTrackIntegerProperty(fileHandle, Id, "edts.elst.version", &editListVersion); + + if (editListVersion == 0 && editMediaTime == ((uint32_t)-1)) + MP4DeleteTrackEdit(fileHandle, Id, 1); + else if (editListVersion == 1 && editMediaTime == ((uint64_t)-1)) + MP4DeleteTrackEdit(fileHandle, Id, 1); + else + break; + } + // If there is already an edit list reuse it + if (MP4GetTrackNumberOfEdits(fileHandle, Id)) { + + MP4Duration oldEditDuration = MP4GetTrackEditDuration(fileHandle, Id, 1); + MP4Duration oldEditMediaStart = MP4GetTrackEditMediaStart(fileHandle, Id, 1); + oldEditMediaStart = MP4ConvertFromTrackDuration(fileHandle, + Id, + oldEditMediaStart, + MP4GetTimeScale(fileHandle)); + MP4Duration newOffsetDuration = MP4ConvertFromTrackDuration(fileHandle, + Id, + -offset, + MP4GetTimeScale(fileHandle)); + + MP4SetTrackEditDuration(fileHandle, Id, 1, oldEditDuration + oldEditMediaStart - newOffsetDuration); + MP4SetTrackEditMediaStart(fileHandle, Id, 1, -offset); + } + // Else create a new one. + else { + MP4Duration delayDuration = MP4ConvertFromTrackDuration(fileHandle, + Id, + -offset, + MP4GetTimeScale(fileHandle)); + + MP4AddTrackEdit(fileHandle, Id, 1, -1, delayDuration, 0); + } + } + } + + // Update the duration in tkhd, the value must be the sum of the durations of all track's edits. + MP4Duration totalDuration = getTrackDuration(fileHandle, Id); + MP4SetTrackIntegerProperty(fileHandle, Id, "tkhd.duration", totalDuration); + + // Update the duration in mvhd. + updateMoovDuration(fileHandle); +} + +int copyTrackEditLists (MP4FileHandle fileHandle, MP4TrackId srcTrackId, MP4TrackId dstTrackId) { + MP4Duration trackDuration = 0; + uint32_t i = 1, trackEditCount = MP4GetTrackNumberOfEdits(fileHandle, srcTrackId); + while (i <= trackEditCount) { + MP4Timestamp editMediaStart = MP4GetTrackEditMediaStart(fileHandle, srcTrackId, i); + MP4Duration editDuration = MP4ConvertFromMovieDuration(fileHandle, + MP4GetTrackEditDuration(fileHandle, srcTrackId, i), + MP4GetTimeScale(fileHandle)); + trackDuration += editDuration; + int8_t editDwell = MP4GetTrackEditDwell(fileHandle, srcTrackId, i); + + MP4AddTrackEdit(fileHandle, dstTrackId, i, editMediaStart, editDuration, editDwell); + i++; + } + if (trackEditCount) + MP4SetTrackIntegerProperty(fileHandle, dstTrackId, "tkhd.duration", trackDuration); + else { + uint32_t firstFrameOffset = MP4GetSampleRenderingOffset(fileHandle, dstTrackId, 1); + MP4Duration editDuration = MP4ConvertFromTrackDuration(fileHandle, + srcTrackId, + MP4GetTrackDuration(fileHandle, srcTrackId), + MP4GetTimeScale(fileHandle)); + MP4AddTrackEdit(fileHandle, dstTrackId, MP4_INVALID_EDIT_ID, firstFrameOffset, + editDuration, 0); + } + + return 1; +} + +NSError* MP42Error(NSString *description, NSString* recoverySuggestion, NSInteger code) { + NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary]; + [errorDetail setValue:description + forKey:NSLocalizedDescriptionKey]; + [errorDetail setValue:recoverySuggestion + forKey:NSLocalizedRecoverySuggestionErrorKey]; + + return [NSError errorWithDomain:@"MP42Error" + code:code + userInfo:errorDetail]; +} + +// Taken from HandBrake common.c +int yuv2rgb(int yuv) +{ + double y, Cr, Cb; + int r, g, b; + + y = (yuv >> 16) & 0xff; + Cb = (yuv >> 8) & 0xff; + Cr = (yuv ) & 0xff; + + r = 1.164 * (y - 16) + 2.018 * (Cb - 128); + g = 1.164 * (y - 16) - 0.813 * (Cr - 128) - 0.391 * (Cb - 128); + b = 1.164 * (y - 16) + 1.596 * (Cr - 128); + + r = (r < 0) ? 0 : r; + g = (g < 0) ? 0 : g; + b = (b < 0) ? 0 : b; + + r = (r > 255) ? 255 : r; + g = (g > 255) ? 255 : g; + b = (b > 255) ? 255 : b; + + return (r << 16) | (g << 8) | b; +} + +int rgb2yuv(int rgb) +{ + double r, g, b; + int y, Cr, Cb; + + r = (rgb >> 16) & 0xff; + g = (rgb >> 8) & 0xff; + b = (rgb ) & 0xff; + + y = 16. + ( 0.257 * r) + (0.504 * g) + (0.098 * b); + Cb = 128. + (-0.148 * r) - (0.291 * g) + (0.439 * b); + Cr = 128. + ( 0.439 * r) - (0.368 * g) - (0.071 * b); + + y = (y < 0) ? 0 : y; + Cb = (Cb < 0) ? 0 : Cb; + Cr = (Cr < 0) ? 0 : Cr; + + y = (y > 255) ? 255 : y; + Cb = (Cb > 255) ? 255 : Cb; + Cr = (Cr > 255) ? 255 : Cr; + + return (y << 16) | (Cr << 8) | Cb; +} + +void *fast_realloc_with_padding(void *ptr, unsigned int *size, unsigned int min_size) +{ + void *res = ptr; + av_fast_malloc(&res, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE); + if (res) memset(res + min_size, 0, FF_INPUT_BUFFER_PADDING_SIZE); + return res; +} + +int DecompressZlib(uint8_t **sampleData, uint32_t *sampleSize) +{ + uint8_t* pkt_data = NULL; + uint8_t av_unused *newpktdata; + int pkt_size = *sampleSize; + int result = 0; + + z_stream zstream = {0}; + if (inflateInit(&zstream) != Z_OK) + return 0; + zstream.next_in = *sampleData; + zstream.avail_in = *sampleSize; + do { + pkt_size *= 3; + newpktdata = av_realloc(pkt_data, pkt_size); + if (!newpktdata) { + inflateEnd(&zstream); + goto failed; + } + pkt_data = newpktdata; + zstream.avail_out = pkt_size - zstream.total_out; + zstream.next_out = pkt_data + zstream.total_out; + if (pkt_data) { + result = inflate(&zstream, Z_NO_FLUSH); + } else + result = Z_MEM_ERROR; + } while (result==Z_OK && pkt_size<10000000); + pkt_size = zstream.total_out; + inflateEnd(&zstream); + if (result != Z_STREAM_END) { + if (result == Z_MEM_ERROR) + result = 0; + else + result = 0; + goto failed; + } + + if (*sampleData) + free(*sampleData); + + *sampleData = pkt_data; + *sampleSize = pkt_size; + return 1; + +failed: + av_free(pkt_data); + return result; +} + +int DecompressBzlib(uint8_t **sampleData, uint32_t *sampleSize) +{ + uint8_t* pkt_data = NULL; + uint8_t av_unused *newpktdata; + int pkt_size = *sampleSize; + int result = 0; + + bz_stream bzstream = {0}; + if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK) + return 0; + bzstream.next_in = (char *) *sampleData; + bzstream.avail_in = *sampleSize; + do { + pkt_size *= 3; + newpktdata = av_realloc(pkt_data, pkt_size); + if (!newpktdata) { + BZ2_bzDecompressEnd(&bzstream); + goto failed; + } + pkt_data = newpktdata; + bzstream.avail_out = pkt_size - bzstream.total_out_lo32; + bzstream.next_out = (char *) pkt_data + bzstream.total_out_lo32; + if (pkt_data) { + result = BZ2_bzDecompress(&bzstream); + } else + result = BZ_MEM_ERROR; + } while (result==BZ_OK && pkt_size<10000000); + pkt_size = bzstream.total_out_lo32; + BZ2_bzDecompressEnd(&bzstream); + if (result != BZ_STREAM_END) { + if (result == BZ_MEM_ERROR) + result = 0; + else + result = 0; + goto failed; + } + + if (*sampleData) + free(*sampleData); + + *sampleData = pkt_data; + *sampleSize = pkt_size; + return 1; + +failed: + av_free(pkt_data); + return result; +} diff --git a/MP42/MP42VideoTrack.h b/MP42/MP42VideoTrack.h new file mode 100644 index 0000000..5c16636 --- /dev/null +++ b/MP42/MP42VideoTrack.h @@ -0,0 +1,59 @@ +// +// MP42VideoTrack.h +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import +#import "MP42Track.h" + +@interface MP42VideoTrack : MP42Track { + uint64_t width, height; + float trackWidth, trackHeight; + + // Pixel Aspect Ratio + uint64_t hSpacing, vSpacing; + + // Clean Aperture + uint64_t cleanApertureWidthN, cleanApertureWidthD; + uint64_t cleanApertureHeightN, cleanApertureHeightD; + uint64_t horizOffN, horizOffD; + uint64_t vertOffN, vertOffD; + + // Matrix + uint32_t offsetX, offsetY; + + // H.264 profile + uint8_t _origProfile, _origLevel; + uint8_t _newProfile, _newLevel; +} + +@property(nonatomic, readwrite) uint64_t width; +@property(nonatomic, readwrite) uint64_t height; + +@property(nonatomic, readwrite) float trackWidth; +@property(nonatomic, readwrite) float trackHeight; + +@property(nonatomic, readwrite) uint64_t hSpacing; +@property(nonatomic, readwrite) uint64_t vSpacing; + +@property(nonatomic, readwrite) uint64_t cleanApertureWidthN; +@property(nonatomic, readwrite) uint64_t cleanApertureWidthD; +@property(nonatomic, readwrite) uint64_t cleanApertureHeightN; +@property(nonatomic, readwrite) uint64_t cleanApertureHeightD; +@property(nonatomic, readwrite) uint64_t horizOffN; +@property(nonatomic, readwrite) uint64_t horizOffD; +@property(nonatomic, readwrite) uint64_t vertOffN; +@property(nonatomic, readwrite) uint64_t vertOffD; + +@property(nonatomic, readwrite) uint32_t offsetX; +@property(nonatomic, readwrite) uint32_t offsetY; + +@property(nonatomic, readwrite) uint8_t origProfile; +@property(nonatomic, readwrite) uint8_t origLevel; +@property(nonatomic, readwrite) uint8_t newProfile; +@property(nonatomic, readwrite) uint8_t newLevel; + +@end diff --git a/MP42/MP42VideoTrack.m b/MP42/MP42VideoTrack.m new file mode 100644 index 0000000..a5dfb17 --- /dev/null +++ b/MP42/MP42VideoTrack.m @@ -0,0 +1,283 @@ +// +// MP42SubtitleTrack.m +// Subler +// +// Created by Damiano Galassi on 31/01/09. +// Copyright 2009 Damiano Galassi. All rights reserved. +// + +#import "MP42VideoTrack.h" +#import "MP42MediaFormat.h" +#import + +@implementation MP42VideoTrack + +- (instancetype)initWithSourceURL:(NSURL *)URL trackID:(NSInteger)trackID fileHandle:(MP42FileHandle)fileHandle +{ + if ((self = [super initWithSourceURL:URL trackID:trackID fileHandle:fileHandle])) { + if ([self isMemberOfClass:[MP42VideoTrack class]]) { + height = MP4GetTrackVideoHeight(fileHandle, _Id); + width = MP4GetTrackVideoWidth(fileHandle, _Id); + } + + _mediaType = MP42MediaTypeVideo; + + MP4GetTrackFloatProperty(fileHandle, _Id, "tkhd.width", &trackWidth); + MP4GetTrackFloatProperty(fileHandle, _Id, "tkhd.height", &trackHeight); + + uint8_t *val; + uint8_t nval[36]; + uint32_t *ptr32 = (uint32_t*) nval; + uint32_t size; + + MP4GetTrackBytesProperty(fileHandle ,_Id, "tkhd.matrix", &val, &size); + memcpy(nval, val, size); + offsetX = CFSwapInt32BigToHost(ptr32[6]) / 0x10000; + offsetY = CFSwapInt32BigToHost(ptr32[7]) / 0x10000; + free(val); + + if (MP4HaveTrackAtom(fileHandle, _Id, "mdia.minf.stbl.stsd.*.pasp")) { + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.pasp.hSpacing", &hSpacing); + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.pasp.vSpacing", &vSpacing); + } + else { + hSpacing = 1; + vSpacing = 1; + } + + if (MP4HaveTrackAtom(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap")) { + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.cleanApertureWidthN", &cleanApertureWidthN); + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.cleanApertureWidthD", &cleanApertureWidthD); + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.cleanApertureHeightN", &cleanApertureHeightN); + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.cleanApertureHeightD", &cleanApertureHeightD); + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.horizOffN", &horizOffN); + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.horizOffD", &horizOffD); + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.vertOffN", &vertOffN); + MP4GetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.vertOffD", &vertOffD); + } + + if ([_format isEqualToString:MP42VideoFormatH264]) { + MP4GetTrackH264ProfileLevel(fileHandle, (MP4TrackId)trackID, &_origProfile, &_origLevel); + _newProfile = _origProfile; + _newLevel = _origLevel; + } + } + + return self; +} + +- (instancetype)init +{ + if ((self = [super init])) { + _name = [self defaultName]; + _language = @"Unknown"; + _mediaType = MP42MediaTypeVideo; + } + + return self; +} + +- (BOOL)writeToFile:(MP4FileHandle)fileHandle error:(NSError **)outError +{ + if (!fileHandle) + return NO; + + if (_Id) { + [super writeToFile:fileHandle error:outError]; + + if (trackWidth && trackHeight) { + MP4SetTrackFloatProperty(fileHandle, _Id, "tkhd.width", trackWidth); + + MP4SetTrackFloatProperty(fileHandle, _Id, "tkhd.height", trackHeight); + + uint8_t *val; + uint8_t nval[36]; + uint32_t *ptr32 = (uint32_t*) nval; + uint32_t size; + + MP4GetTrackBytesProperty(fileHandle ,_Id, "tkhd.matrix", &val, &size); + memcpy(nval, val, size); + ptr32[6] = CFSwapInt32HostToBig(offsetX * 0x10000); + ptr32[7] = CFSwapInt32HostToBig(offsetY * 0x10000); + MP4SetTrackBytesProperty(fileHandle, _Id, "tkhd.matrix", nval, size); + + free(val); + + if ([_updatedProperty valueForKey:@"hSpacing"] || [_updatedProperty valueForKey:@"vSpacing"]) { + if (hSpacing >= 1 && vSpacing >= 1) { + if (MP4HaveTrackAtom(fileHandle, _Id, "mdia.minf.stbl.stsd.*.pasp")) { + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.pasp.hSpacing", hSpacing); + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.pasp.vSpacing", vSpacing); + } + else + MP4AddPixelAspectRatio(fileHandle, _Id, (uint32_t)hSpacing, (uint32_t)vSpacing); + } + } + + if (cleanApertureWidthN >= 1 && cleanApertureHeightN >= 1) { + if (MP4HaveTrackAtom(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap")) { + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.cleanApertureWidthN", cleanApertureWidthN); + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.cleanApertureWidthD", cleanApertureWidthD); + + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.cleanApertureHeightN", cleanApertureHeightN); + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.cleanApertureHeightD", cleanApertureHeightD); + + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.horizOffN", horizOffN); + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.horizOffD", horizOffD); + + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.vertOffN", vertOffN); + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*.clap.vertOffD", vertOffD); + } + else + MP4AddCleanAperture(fileHandle, _Id, cleanApertureWidthN, cleanApertureWidthD, cleanApertureHeightN, cleanApertureHeightD, + horizOffN, horizOffD, vertOffN, vertOffD); + } + + if ([_format isEqualToString:MP42VideoFormatH264]) { + if ([_updatedProperty valueForKey:@"profile"]) { + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*[0].avcC.AVCProfileIndication", _newProfile); + _origProfile = _newProfile; + } + if ([_updatedProperty valueForKey:@"level"]) { + MP4SetTrackIntegerProperty(fileHandle, _Id, "mdia.minf.stbl.stsd.*[0].avcC.AVCLevelIndication", _newLevel); + _origLevel = _newLevel; + } + } + } + } + + return _Id; +} + +- (NSString *)defaultName { + return MP42MediaTypeVideo; +} + +- (void)dealloc +{ + [super dealloc]; +} + +@synthesize width; +@synthesize height; + +@synthesize trackWidth; +@synthesize trackHeight; + + +- (uint64_t)hSpacing { + return hSpacing; +} + +- (void)setHSpacing:(uint64_t)newHSpacing +{ + hSpacing = newHSpacing; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"hSpacing"]; +} + +- (uint64_t)vSpacing { + return vSpacing; +} + +- (void)setVSpacing:(uint64_t)newVSpacing +{ + vSpacing = newVSpacing; + _isEdited = YES; + [_updatedProperty setValue:@"True" forKey:@"vSpacing"]; +} + +@synthesize offsetX; +@synthesize offsetY; + +@synthesize cleanApertureHeightD, cleanApertureHeightN, cleanApertureWidthD, cleanApertureWidthN; +@synthesize horizOffD, horizOffN, vertOffD, vertOffN; + +@synthesize origProfile = _origProfile; +@synthesize origLevel = _origLevel; + +- (uint8_t)newProfile { + return _newProfile; +} + +- (void)setNewProfile:(uint8_t)newProfile +{ + _newProfile = newProfile; + _isEdited = YES; + + if (_newProfile == _origProfile) + [_updatedProperty setValue:@"False" forKey:@"profile"]; + else + [_updatedProperty setValue:@"True" forKey:@"profile"]; +} + +- (uint8_t)newLevel { + return _newLevel; +} + +- (void)setNewLevel:(uint8_t)newLevel +{ + _newLevel = newLevel; + _isEdited = YES; + + if (_newLevel == _origLevel) + [_updatedProperty setValue:@"False" forKey:@"level"]; + else + [_updatedProperty setValue:@"True" forKey:@"level"]; +} + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [super encodeWithCoder:coder]; + + [coder encodeInt:1 forKey:@"MP42VideoTrackVersion"]; + + [coder encodeInt64:width forKey:@"width"]; + [coder encodeInt64:height forKey:@"height"]; + + [coder encodeFloat:trackWidth forKey:@"trackWidth"]; + [coder encodeFloat:trackHeight forKey:@"trackHeight"]; + + [coder encodeInt64:hSpacing forKey:@"hSpacing"]; + [coder encodeInt64:vSpacing forKey:@"vSpacing"]; + + [coder encodeInt32:offsetX forKey:@"offsetX"]; + [coder encodeInt32:offsetY forKey:@"offsetY"]; + + [coder encodeInt:_origProfile forKey:@"origProfile"]; + [coder encodeInt:_origLevel forKey:@"origLevel"]; + + [coder encodeInt:_newProfile forKey:@"newProfile"]; + [coder encodeInt:_newLevel forKey:@"newLevel"]; +} + +- (id)initWithCoder:(NSCoder *)decoder +{ + self = [super initWithCoder:decoder]; + + width = [decoder decodeInt64ForKey:@"width"]; + height = [decoder decodeInt64ForKey:@"height"]; + + trackWidth = [decoder decodeFloatForKey:@"trackWidth"]; + trackHeight = [decoder decodeFloatForKey:@"trackHeight"]; + + hSpacing = [decoder decodeInt64ForKey:@"hSpacing"]; + vSpacing = [decoder decodeInt64ForKey:@"vSpacing"]; + + offsetX = [decoder decodeInt32ForKey:@"offsetX"]; + offsetY = [decoder decodeInt32ForKey:@"offsetY"]; + + _origProfile = [decoder decodeInt32ForKey:@"origProfile"]; + _origLevel = [decoder decodeInt32ForKey:@"origLevel"]; + + _newProfile = [decoder decodeInt32ForKey:@"newProfile"]; + _newLevel = [decoder decodeInt32ForKey:@"newLevel"]; + + return self; +} + +- (NSString *)description { + return [[super description] stringByAppendingFormat:@", %lld x %lld", width, height]; +} + +@end diff --git a/MP42/MP42VobSubImporter.h b/MP42/MP42VobSubImporter.h new file mode 100644 index 0000000..42120ac --- /dev/null +++ b/MP42/MP42VobSubImporter.h @@ -0,0 +1,15 @@ +// +// SBVobSubImpoter.h +// Subler +// +// Created by Damiano Galassi on 20/12/12. +// +// + +#import "MP42FileImporter.h" + +@interface MP42VobSubImporter : MP42FileImporter { + NSArray *_VobSubTracks; +} + +@end diff --git a/MP42/MP42VobSubImporter.m b/MP42/MP42VobSubImporter.m new file mode 100644 index 0000000..143ecc9 --- /dev/null +++ b/MP42/MP42VobSubImporter.m @@ -0,0 +1,404 @@ +// +// SBVobSubImpoter.m +// Subler +// +// Created by Damiano Galassi on 20/12/12. +// Based on parts of Perian's source code. +// + +#import "MP42VobSubImporter.h" +#import "MP42SubUtilities.h" +#import "SBLanguages.h" +#import "MP42File.h" + + +@interface SBVobSubSample : NSObject +{ +@public + long timeStamp; + long fileOffset; +} + +- (id)initWithTime:(long)time offset:(long)offset; +@end + +@interface SBVobSubTrack : NSObject +{ +@public + NSArray *privateData; + NSString *language; + int index; + long duration; + NSMutableArray *samples; +} + +- (id)initWithPrivateData:(NSArray *)idxPrivateData language:(NSString *)lang andIndex:(int)trackIndex; +- (void)addSample:(SBVobSubSample *)sample; +- (void)addSampleTime:(long)time offset:(long)offset; + +@end + +@implementation SBVobSubSample + +- (id)initWithTime:(long)time offset:(long)offset +{ + self = [super init]; + if(!self) + return self; + + timeStamp = time; + fileOffset = offset; + + return self; +} + +@end + +@implementation SBVobSubTrack + +- (id)initWithPrivateData:(NSArray *)idxPrivateData language:(NSString *)lang andIndex:(int)trackIndex +{ + self = [super init]; + if(!self) + return self; + + privateData = [idxPrivateData retain]; + language = [lang retain]; + index = trackIndex; + samples = [[NSMutableArray alloc] init]; + + return self; +} + +- (void)dealloc +{ + [privateData release]; + [language release]; + [samples release]; + [super dealloc]; +} + +- (void)addSample:(SBVobSubSample *)sample +{ + [samples addObject:sample]; + duration = sample->timeStamp; +} + +- (void)addSampleTime:(long)time offset:(long)offset +{ + SBVobSubSample *sample = [[SBVobSubSample alloc] initWithTime:time offset:offset]; + [self addSample:sample]; + [sample release]; +} + +@end + +typedef enum { + VOB_SUB_STATE_READING_PRIVATE, + VOB_SUB_STATE_READING_TRACK_HEADER, + VOB_SUB_STATE_READING_DELAY, + VOB_SUB_STATE_READING_TRACK_DATA +} VobSubState; + +static NSString *getNextVobSubLine(NSEnumerator *lineEnum) +{ + NSString *line; + while ((line = [lineEnum nextObject]) != nil) { + //Reject empty lines which may contain whitespace + if([line length] < 3) + continue; + + if([line characterAtIndex:0] == '#') + continue; + + break; + } + return line; +} + +static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename) +{ + @autoreleasepool { + NSString *nsPath = [[theDirectory path] stringByAppendingPathComponent:filename]; + NSString *idxContent = STLoadFileWithUnknownEncoding(nsPath); + NSData *privateData = nil; + + VobSubState state = VOB_SUB_STATE_READING_PRIVATE; + SBVobSubTrack *currentTrack = nil; + int imageWidth = 0, imageHeight = 0; + long delay=0; + + NSString *subFileName = [[nsPath stringByDeletingPathExtension] stringByAppendingPathExtension:@"sub"]; + + if([idxContent length]) { + NSError *nsErr; + NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:subFileName error:&nsErr]; + if (!attr) goto bail; + int subFileSize = [[attr objectForKey:NSFileSize] intValue]; + + NSArray *lines = [idxContent componentsSeparatedByString:@"\n"]; + NSMutableArray *privateLines = [NSMutableArray array]; + NSEnumerator *lineEnum = [lines objectEnumerator]; + NSString *line; + + NSMutableArray *tracks = [NSMutableArray array]; + + while((line = getNextVobSubLine(lineEnum)) != NULL) + { + if([line hasPrefix:@"timestamp: "]) + state = VOB_SUB_STATE_READING_TRACK_DATA; + else if([line hasPrefix:@"id: "]) + { + if(privateData == nil) + { + NSString *allLines = [privateLines componentsJoinedByString:@"\n"]; + privateData = [allLines dataUsingEncoding:NSUTF8StringEncoding]; + } + state = VOB_SUB_STATE_READING_TRACK_HEADER; + } + else if([line hasPrefix:@"delay: "]) + state = VOB_SUB_STATE_READING_DELAY; + else if(state != VOB_SUB_STATE_READING_PRIVATE) + state = VOB_SUB_STATE_READING_TRACK_HEADER; + + switch(state) + { + case VOB_SUB_STATE_READING_PRIVATE: + [privateLines addObject:line]; + if([line hasPrefix:@"size: "]) + { + sscanf([line UTF8String], "size: %dx%d", &imageWidth, &imageHeight); + } + break; + case VOB_SUB_STATE_READING_TRACK_HEADER: + if([line hasPrefix:@"id: "]) + { + char *langStr = (char *)malloc([line length]); + int index; + sscanf([line UTF8String], "id: %s index: %d", langStr, &index); + size_t langLength = strlen(langStr); + if(langLength > 0 && langStr[langLength-1] == ',') + langStr[langLength-1] = 0; + NSString *language = [NSString stringWithUTF8String:langStr]; + free(langStr); + + currentTrack = [[SBVobSubTrack alloc] initWithPrivateData:privateLines language:language andIndex:index]; + [tracks addObject:currentTrack]; + [currentTrack release]; + } + break; + case VOB_SUB_STATE_READING_DELAY: + delay = ParseSubTime([[line substringFromIndex:7] UTF8String], 1000, YES); + break; + case VOB_SUB_STATE_READING_TRACK_DATA: + { + char *timeStr = (char *)malloc([line length]); + unsigned int position; + sscanf([line UTF8String], "timestamp: %s filepos: %x", timeStr, &position); + long time = ParseSubTime(timeStr, 1000, YES); + free(timeStr); + if(position > subFileSize) + position = subFileSize; + [currentTrack addSampleTime:time + delay offset:position]; + } + break; + } + } + + return [tracks retain]; + } + bail: + ; + NSLog(@"Exception occurred while importing VobSub"); + return nil; + } +} + +@implementation MP42VobSubImporter + +- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError **)outError +{ + if ((self = [super init])) { + NSInteger count = 0; + _fileURL = [fileURL retain]; + + _VobSubTracks = LoadVobSubSubtitles([_fileURL URLByDeletingLastPathComponent], [_fileURL lastPathComponent]); + _tracksArray = [[NSMutableArray alloc] initWithCapacity:[_VobSubTracks count]]; + + for (SBVobSubTrack *track in _VobSubTracks) { + MP42SubtitleTrack *newTrack = [[MP42SubtitleTrack alloc] init]; + + newTrack.format = MP42SubtitleFormatVobSub; + newTrack.sourceURL = _fileURL; + newTrack.alternate_group = 2; + newTrack.Id = count++; + newTrack.language = [NSString stringWithFormat:@"%s", lang_for_code_s([track->language UTF8String])->eng_name];; + newTrack.duration = track->duration; + + [_tracksArray addObject:newTrack]; + [newTrack release]; + } + + if (![_tracksArray count]) { + if (outError) + *outError = MP42Error(@"The file could not be opened.", @"The file is not a idx file, or it does not contain any subtitles.", 100); + + [self release]; + return nil; + } + } + + return self; +} + +- (NSUInteger)timescaleForTrack:(MP42Track *)track +{ + return 1000; +} + +- (NSSize)sizeForTrack:(MP42Track *)track +{ + return NSMakeSize([(MP42SubtitleTrack*)track trackWidth], [(MP42SubtitleTrack*) track trackHeight]); +} + +- (NSData*)magicCookieForTrack:(MP42Track *)track +{ + SBVobSubTrack *vobTrack = [_VobSubTracks objectAtIndex:track.sourceId]; + NSMutableData *magicCookie = nil; + + for (NSString *line in vobTrack->privateData) { + if([line hasPrefix:@"palette: "]) { + const char *palette = [line UTF8String]; + UInt32 colorPalette[16]; + + if (palette != NULL) { + sscanf(palette, "palette: %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx", + &colorPalette[ 0], &colorPalette[ 1], &colorPalette[ 2], &colorPalette[ 3], + &colorPalette[ 4], &colorPalette[ 5], &colorPalette[ 6], &colorPalette[ 7], + &colorPalette[ 8], &colorPalette[ 9], &colorPalette[10], &colorPalette[11], + &colorPalette[12], &colorPalette[13], &colorPalette[14], &colorPalette[15]); + } + magicCookie = [NSData dataWithBytes:colorPalette length:sizeof(UInt32)*16]; + } + } + + return magicCookie; +} + +- (void)demux:(id)sender +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + NSURL *subFileURL = [[_fileURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sub"]; + + NSData *subFileData = [NSData dataWithContentsOfURL:subFileURL]; + + NSInteger tracksNumber = [_inputTracks count]; + NSInteger tracksDone = 0; + + for (MP42Track *track in _inputTracks) { + SBVobSubTrack *vobTrack = [_VobSubTracks objectAtIndex:track.sourceId]; + SBVobSubSample *firstSample = nil; + + uint32_t lastTime = 0; + int i, sampleCount = [vobTrack->samples count]; + + for (i = 0; i < sampleCount && !_cancelled; i++) { + SBVobSubSample *currentSample = [vobTrack->samples objectAtIndex:i]; + int offset = currentSample->fileOffset; + int nextOffset; + if(i == sampleCount - 1) + nextOffset = [subFileData length]; + else + nextOffset = ((SBVobSubSample *)[vobTrack->samples objectAtIndex:i+1])->fileOffset; + int size = nextOffset - offset; + if(size < 0) + //Skip samples for which we cannot determine size + continue; + + NSData *subData = [subFileData subdataWithRange:NSMakeRange(offset, size)]; + uint8_t *extracted = (uint8_t *)malloc(size); + //The index here likely should really be track->index, but I'm not sure we can really trust it. + int extractedSize = ExtractVobSubPacket(extracted, (UInt8 *)[subData bytes], size, &size, -1); + + uint16_t startTimestamp, endTimestamp; + uint8_t forced; + if(!ReadPacketTimes(extracted, extractedSize, &startTimestamp, &endTimestamp, &forced)) { + free(extracted); + continue; + } + + uint32_t startTime = currentSample->timeStamp + startTimestamp; + uint32_t endTime = currentSample->timeStamp + endTimestamp; + + int duration = endTimestamp - startTimestamp; + if(duration <= 0 && i <= sampleCount - 1) { + //Sample with no end duration, use the duration of the next one + endTime = ((SBVobSubSample *)[vobTrack->samples objectAtIndex:i+1])->timeStamp; + duration = endTime - startTime; + } + if(duration <= 0) { + //Skip samples which are broken + free(extracted); + continue; + } + if(firstSample == nil) { + currentSample->timeStamp = startTime; + firstSample = currentSample; + } + if(lastTime != startTime) { + //insert a sample with no real data, to clear the subs + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->size = 2; + sample->data = calloc(1, 2); + sample->duration = startTime - lastTime; + sample->offset = 0; + sample->timestamp = startTime; + sample->isSync = YES; + sample->trackId = track.sourceId; + + [self enqueue:sample]; + [sample release]; + } + + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = extracted; + sample->size = size; + sample->duration = duration; + sample->offset = 0; + sample->timestamp = startTime; + sample->isSync = YES; + sample->trackId = track.sourceId; + + [self enqueue:sample]; + [sample release]; + + lastTime = endTime; + + _progress = ((i / (CGFloat) sampleCount ) * 100 / tracksNumber) + (tracksDone / (CGFloat) tracksNumber * 100); + } + tracksDone++; + } + + [self setDone:YES]; + [pool release]; +} + +- (void)startReading +{ + [super startReading]; + + if (!_demuxerThread && !_done) { + _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; + [_demuxerThread setName:@"VobSub Demuxer"]; + [_demuxerThread start]; + } +} + +- (void) dealloc +{ + [_VobSubTracks release]; + + [super dealloc]; +} + +@end diff --git a/MP42/MP42XMLReader.h b/MP42/MP42XMLReader.h new file mode 100644 index 0000000..6040d21 --- /dev/null +++ b/MP42/MP42XMLReader.h @@ -0,0 +1,21 @@ +// +// MP42XMLReader.h +// Subler +// +// Created by Damiano Galassi on 25/01/13. +// +// + +#import + +@class MP42Metadata; + +@interface MP42XMLReader : NSObject { + MP42Metadata *mMetadata; +} + +- (instancetype)initWithURL:(NSURL *)url error:(NSError **)error; + +@property(readonly) MP42Metadata *mMetadata; + +@end diff --git a/MP42/MP42XMLReader.m b/MP42/MP42XMLReader.m new file mode 100644 index 0000000..c277b22 --- /dev/null +++ b/MP42/MP42XMLReader.m @@ -0,0 +1,134 @@ +// +// MP42XMLReader.m +// Subler +// +// Created by Damiano Galassi on 25/01/13. +// +// + +#import "MP42XMLReader.h" +#import "MP42Metadata.h" + +@implementation MP42XMLReader + +@synthesize mMetadata; + +- (instancetype)initWithURL:(NSURL *)url error:(NSError **)error +{ + if (self = [super init]) { + NSXMLDocument *xml = [[NSXMLDocument alloc] initWithContentsOfURL:url options:0 error:NULL]; + if (xml) { + NSError *err; + mMetadata = [[MP42Metadata alloc] init]; + NSArray *nodes = [xml nodesForXPath:@"./movie" error:&err]; + if ([nodes count] == 1) + [self metadata:mMetadata forNode:[nodes objectAtIndex:0]]; + + nodes = [xml nodesForXPath:@"./video" error:&err]; + if ([nodes count] == 1) + [self metadata2:mMetadata forNode:[nodes objectAtIndex:0]]; + } + [xml release]; + } + return self; +} + +#pragma mark Parse metadata + +- (NSString *) nodes:(NSXMLElement *)node forXPath:(NSString *)query joinedBy:(NSString *)joiner { + NSError *err; + NSArray *tag = [node nodesForXPath:query error:&err]; + if ([tag count]) { + NSMutableArray *elements = [[[NSMutableArray alloc] initWithCapacity:[tag count]] autorelease]; + NSEnumerator *tagEnum = [tag objectEnumerator]; + NSXMLNode *element; + while ((element = [tagEnum nextObject])) { + [elements addObject:[element stringValue]]; + } + return [elements componentsJoinedByString:@", "]; + } else { + return nil; + } +} + +- (MP42Metadata *) metadata:(MP42Metadata *)metadata forNode:(NSXMLElement *)node { + metadata.mediaKind = 9; // movie + NSArray *tag; + NSError *err; + // initial fields from general movie search + tag = [node nodesForXPath:@"./title" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Name"]; + tag = [node nodesForXPath:@"./year" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Release Date"]; + tag = [node nodesForXPath:@"./outline" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Description"]; + tag = [node nodesForXPath:@"./plot" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Long Description"]; + tag = [node nodesForXPath:@"./certification" error:&err]; + if ([tag count] && [[[tag objectAtIndex:0] stringValue] length]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Rating"]; + tag = [node nodesForXPath:@"./genre" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Genre"]; + tag = [node nodesForXPath:@"./credits" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Artist"]; + tag = [node nodesForXPath:@"./director" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Director"]; + tag = [node nodesForXPath:@"./studio" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Studio"]; + + // additional fields from detailed movie info + NSString *joined; + joined = [self nodes:node forXPath:@"./cast/actor/@name" joinedBy:@","]; + if (joined) [metadata setTag:joined forKey:@"Cast"]; + + return metadata; +} + +- (MP42Metadata *) metadata2:(MP42Metadata *)metadata forNode:(NSXMLElement *)node { + metadata.mediaKind = 9; // movie + NSArray *tag; + NSError *err; + // initial fields from general movie search + tag = [node nodesForXPath:@"./content_id" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"contentID"]; + tag = [node nodesForXPath:@"./genre" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Genre"]; + tag = [node nodesForXPath:@"./name" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Name"]; + tag = [node nodesForXPath:@"./release_date" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Release Date"]; + tag = [node nodesForXPath:@"./encoding_tool" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Encoding Tool"]; + tag = [node nodesForXPath:@"./copyright" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Copyright"]; + + NSString *joined; + joined = [self nodes:node forXPath:@"./producers/producer_name" joinedBy:@","]; + if (joined) [metadata setTag:joined forKey:@"Producers"]; + + joined = [self nodes:node forXPath:@"./directors/director_name" joinedBy:@","]; + if (joined) [metadata setTag:joined forKey:@"Director"], [metadata setTag:joined forKey:@"Artist"]; + + joined = [self nodes:node forXPath:@"./casts/cast" joinedBy:@","]; + if (joined) [metadata setTag:joined forKey:@"Cast"]; + + tag = [node nodesForXPath:@"./studio" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Studio"]; + tag = [node nodesForXPath:@"./description" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Description"]; + tag = [node nodesForXPath:@"./long_description" error:&err]; + if ([tag count]) [metadata setTag:[[tag objectAtIndex:0] stringValue] forKey:@"Long Description"]; + + joined = [self nodes:node forXPath:@"./categories/category" joinedBy:@","]; + if (joined) [metadata setTag:joined forKey:@"Category"]; + + return metadata; +} + + +- (void)dealloc +{ + [mMetadata release]; + [super dealloc]; +} + +@end diff --git a/MP42/RegexKitLite.h b/MP42/RegexKitLite.h new file mode 100644 index 0000000..d467702 --- /dev/null +++ b/MP42/RegexKitLite.h @@ -0,0 +1,295 @@ +// +// RegexKitLite.h +// http://regexkit.sourceforge.net/ +// Licensed under the terms of the BSD License, as specified below. +// + +/* + Copyright (c) 2008-2010, John Engelhart + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the Zang Industries nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifdef __OBJC__ +#import +#import +#import +#import +#import +#endif // __OBJC__ + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef REGEXKITLITE_VERSION_DEFINED +#define REGEXKITLITE_VERSION_DEFINED + +#define _RKL__STRINGIFY(b) #b +#define _RKL_STRINGIFY(a) _RKL__STRINGIFY(a) +#define _RKL_JOIN_VERSION(a,b) _RKL_STRINGIFY(a##.##b) +#define _RKL_VERSION_STRING(a,b) _RKL_JOIN_VERSION(a,b) + +#define REGEXKITLITE_VERSION_MAJOR 4 +#define REGEXKITLITE_VERSION_MINOR 0 + +#define REGEXKITLITE_VERSION_CSTRING _RKL_VERSION_STRING(REGEXKITLITE_VERSION_MAJOR, REGEXKITLITE_VERSION_MINOR) +#define REGEXKITLITE_VERSION_NSSTRING @REGEXKITLITE_VERSION_CSTRING + +#endif // REGEXKITLITE_VERSION_DEFINED + +#if !defined(RKL_BLOCKS) && defined(NS_BLOCKS_AVAILABLE) && (NS_BLOCKS_AVAILABLE == 1) +#define RKL_BLOCKS 1 +#endif + +#if defined(RKL_BLOCKS) && (RKL_BLOCKS == 1) +#define _RKL_BLOCKS_ENABLED 1 +#endif // defined(RKL_BLOCKS) && (RKL_BLOCKS == 1) + +#if defined(_RKL_BLOCKS_ENABLED) && !defined(__BLOCKS__) +#warning RegexKitLite support for Blocks is enabled, but __BLOCKS__ is not defined. This compiler may not support Blocks, in which case the behavior is undefined. This will probably cause numerous compiler errors. +#endif // defined(_RKL_BLOCKS_ENABLED) && !defined(__BLOCKS__) + +// For Mac OS X < 10.5. +#ifndef NSINTEGER_DEFINED +#define NSINTEGER_DEFINED +#if defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) +typedef long NSInteger; +typedef unsigned long NSUInteger; +#define NSIntegerMin LONG_MIN +#define NSIntegerMax LONG_MAX +#define NSUIntegerMax ULONG_MAX +#else // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) +typedef int NSInteger; +typedef unsigned int NSUInteger; +#define NSIntegerMin INT_MIN +#define NSIntegerMax INT_MAX +#define NSUIntegerMax UINT_MAX +#endif // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) +#endif // NSINTEGER_DEFINED + +#ifndef RKLREGEXOPTIONS_DEFINED +#define RKLREGEXOPTIONS_DEFINED + +// These must be identical to their ICU regex counterparts. See http://www.icu-project.org/userguide/regexp.html +enum { + RKLNoOptions = 0, + RKLCaseless = 2, + RKLComments = 4, + RKLDotAll = 32, + RKLMultiline = 8, + RKLUnicodeWordBoundaries = 256 +}; +typedef uint32_t RKLRegexOptions; // This must be identical to the ICU 'flags' argument type. + +#endif // RKLREGEXOPTIONS_DEFINED + +#ifndef RKLREGEXENUMERATIONOPTIONS_DEFINED +#define RKLREGEXENUMERATIONOPTIONS_DEFINED + +enum { + RKLRegexEnumerationNoOptions = 0UL, + RKLRegexEnumerationCapturedStringsNotRequired = 1UL << 9, + RKLRegexEnumerationReleaseStringReturnedByReplacementBlock = 1UL << 10, + RKLRegexEnumerationFastCapturedStringsXXX = 1UL << 11, +}; +typedef NSUInteger RKLRegexEnumerationOptions; + +#endif // RKLREGEXENUMERATIONOPTIONS_DEFINED + +#ifndef _REGEXKITLITE_H_ +#define _REGEXKITLITE_H_ + +#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__APPLE_CC__) && (__APPLE_CC__ >= 5465) +#define RKL_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) +#else +#define RKL_DEPRECATED_ATTRIBUTE +#endif + +#if defined(NS_REQUIRES_NIL_TERMINATION) +#define RKL_REQUIRES_NIL_TERMINATION NS_REQUIRES_NIL_TERMINATION +#else // defined(NS_REQUIRES_NIL_TERMINATION) +#define RKL_REQUIRES_NIL_TERMINATION +#endif // defined(NS_REQUIRES_NIL_TERMINATION) + +// This requires a few levels of rewriting to get the desired results. +#define _RKL_CONCAT_2(c,d) c ## d +#define _RKL_CONCAT(a,b) _RKL_CONCAT_2(a,b) + +#ifdef RKL_PREPEND_TO_METHODS +#define RKL_METHOD_PREPEND(x) _RKL_CONCAT(RKL_PREPEND_TO_METHODS, x) +#else // RKL_PREPEND_TO_METHODS +#define RKL_METHOD_PREPEND(x) x +#endif // RKL_PREPEND_TO_METHODS + +// If it looks like low memory notifications might be available, add code to register and respond to them. +// This is (should be) harmless if it turns out that this isn't the case, since the notification that we register for, +// UIApplicationDidReceiveMemoryWarningNotification, is dynamically looked up via dlsym(). +#if ((defined(TARGET_OS_EMBEDDED) && (TARGET_OS_EMBEDDED != 0)) || (defined(TARGET_OS_IPHONE) && (TARGET_OS_IPHONE != 0))) && (!defined(RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS) || (RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS != 0)) +#define RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS 1 +#endif + +#ifdef __OBJC__ + +// NSException exception name. +extern NSString * const RKLICURegexException; + +// NSError error domains and user info keys. +extern NSString * const RKLICURegexErrorDomain; + +extern NSString * const RKLICURegexEnumerationOptionsErrorKey; +extern NSString * const RKLICURegexErrorCodeErrorKey; +extern NSString * const RKLICURegexErrorNameErrorKey; +extern NSString * const RKLICURegexLineErrorKey; +extern NSString * const RKLICURegexOffsetErrorKey; +extern NSString * const RKLICURegexPreContextErrorKey; +extern NSString * const RKLICURegexPostContextErrorKey; +extern NSString * const RKLICURegexRegexErrorKey; +extern NSString * const RKLICURegexRegexOptionsErrorKey; +extern NSString * const RKLICURegexReplacedCountErrorKey; +extern NSString * const RKLICURegexReplacedStringErrorKey; +extern NSString * const RKLICURegexReplacementStringErrorKey; +extern NSString * const RKLICURegexSubjectRangeErrorKey; +extern NSString * const RKLICURegexSubjectStringErrorKey; + +@interface NSString (RegexKitLiteAdditions) + ++ (void)RKL_METHOD_PREPEND(clearStringCache); + +// Although these are marked as deprecated, a bug in GCC prevents a warning from being issues for + class methods. Filed bug with Apple, #6736857. ++ (NSInteger)RKL_METHOD_PREPEND(captureCountForRegex):(NSString *)regex RKL_DEPRECATED_ATTRIBUTE; ++ (NSInteger)RKL_METHOD_PREPEND(captureCountForRegex):(NSString *)regex options:(RKLRegexOptions)options error:(NSError **)error RKL_DEPRECATED_ATTRIBUTE; + +- (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex; +- (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex range:(NSRange)range; +- (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error; + +- (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex; +- (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex inRange:(NSRange)range; +- (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error; + +- (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex; +- (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex capture:(NSInteger)capture; +- (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex inRange:(NSRange)range; +- (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range capture:(NSInteger)capture error:(NSError **)error; + +- (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex; +- (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex capture:(NSInteger)capture; +- (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex inRange:(NSRange)range; +- (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range capture:(NSInteger)capture error:(NSError **)error; + +- (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement; +- (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement range:(NSRange)searchRange; +- (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement options:(RKLRegexOptions)options range:(NSRange)searchRange error:(NSError **)error; + + //// >= 3.0 + +- (NSInteger)RKL_METHOD_PREPEND(captureCount); +- (NSInteger)RKL_METHOD_PREPEND(captureCountWithOptions):(RKLRegexOptions)options error:(NSError **)error; + +- (BOOL)RKL_METHOD_PREPEND(isRegexValid); +- (BOOL)RKL_METHOD_PREPEND(isRegexValidWithOptions):(RKLRegexOptions)options error:(NSError **)error; + +- (void)RKL_METHOD_PREPEND(flushCachedRegexData); + +- (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex; +- (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex capture:(NSInteger)capture; +- (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex range:(NSRange)range; +- (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range capture:(NSInteger)capture error:(NSError **)error; + + +- (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex; +- (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex range:(NSRange)range; +- (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error; + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex; +- (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex range:(NSRange)range; +- (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error; + + //// >= 4.0 + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; +- (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex range:(NSRange)range withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; +- (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; +- (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withFirstKey:(id)firstKey arguments:(va_list)varArgsList; + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeys:(id *)keys forCaptures:(int *)captures count:(NSUInteger)count; + +- (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; +- (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex range:(NSRange)range withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; +- (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; +- (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withFirstKey:(id)firstKey arguments:(va_list)varArgsList; + +- (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeys:(id *)keys forCaptures:(int *)captures count:(NSUInteger)count; + +#ifdef _RKL_BLOCKS_ENABLED + +- (BOOL)RKL_METHOD_PREPEND(enumerateStringsMatchedByRegex):(NSString *)regex usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; +- (BOOL)RKL_METHOD_PREPEND(enumerateStringsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; + +- (BOOL)RKL_METHOD_PREPEND(enumerateStringsSeparatedByRegex):(NSString *)regex usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; +- (BOOL)RKL_METHOD_PREPEND(enumerateStringsSeparatedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; + +- (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; +- (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; + +#endif // _RKL_BLOCKS_ENABLED + +@end + +@interface NSMutableString (RegexKitLiteAdditions) + +- (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement; +- (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement range:(NSRange)searchRange; +- (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement options:(RKLRegexOptions)options range:(NSRange)searchRange error:(NSError **)error; + + //// >= 4.0 + +#ifdef _RKL_BLOCKS_ENABLED + +- (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; +- (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; + +#endif // _RKL_BLOCKS_ENABLED + +@end + +#endif // __OBJC__ + +#endif // _REGEXKITLITE_H_ + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/MP42/RegexKitLite.m b/MP42/RegexKitLite.m new file mode 100644 index 0000000..dababa6 --- /dev/null +++ b/MP42/RegexKitLite.m @@ -0,0 +1,2636 @@ +// +// RegexKitLite.m +// http://regexkit.sourceforge.net/ +// Licensed under the terms of the BSD License, as specified below. +// + +/* + Copyright (c) 2008-2010, John Engelhart + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the Zang Industries nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#include +#import +#import +#import +#import +#import +#import +#ifdef __OBJC_GC__ +#import +#define RKL_STRONG_REF __strong +#define RKL_GC_VOLATILE volatile +#else // __OBJC_GC__ +#define RKL_STRONG_REF +#define RKL_GC_VOLATILE +#endif // __OBJC_GC__ + +#if (defined(TARGET_OS_EMBEDDED) && (TARGET_OS_EMBEDDED != 0)) || (defined(TARGET_OS_IPHONE) && (TARGET_OS_IPHONE != 0)) || (defined(MAC_OS_X_VERSION_MIN_REQUIRED) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) +#include +#else +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#import "RegexKitLite.h" + +// If the gcc flag -mmacosx-version-min is used with, for example, '=10.2', give a warning that the libicucore.dylib is only available on >= 10.3. +// If you are reading this comment because of this warning, this is to let you know that linking to /usr/lib/libicucore.dylib will cause your executable to fail on < 10.3. +// You will need to build your own version of the ICU library and link to that in order for RegexKitLite to work successfully on < 10.3. This is not simple. + +#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030 +#warning The ICU dynamic shared library, /usr/lib/libicucore.dylib, is only available on Mac OS X 10.3 and later. +#warning You will need to supply a version of the ICU library to use RegexKitLite on Mac OS X 10.2 and earlier. +#endif + +//////////// +#pragma mark Compile time tunables + +#ifndef RKL_CACHE_SIZE +#define RKL_CACHE_SIZE (13UL) +#endif + +#if RKL_CACHE_SIZE < 1 +#error RKL_CACHE_SIZE must be a non-negative number greater than 0. +#endif // RKL_CACHE_SIZE < 1 + +#ifndef RKL_FIXED_LENGTH +#define RKL_FIXED_LENGTH (2048UL) +#endif + +#if RKL_FIXED_LENGTH < 1 +#error RKL_FIXED_LENGTH must be a non-negative number greater than 0. +#endif // RKL_FIXED_LENGTH < 1 + +#ifndef RKL_STACK_LIMIT +#define RKL_STACK_LIMIT (128UL * 1024UL) +#endif + +#if RKL_STACK_LIMIT < 0 +#error RKL_STACK_LIMIT must be a non-negative number. +#endif // RKL_STACK_LIMIT < 0 + +#ifdef RKL_APPEND_TO_ICU_FUNCTIONS +#define RKL_ICU_FUNCTION_APPEND(x) _RKL_CONCAT(x, RKL_APPEND_TO_ICU_FUNCTIONS) +#else // RKL_APPEND_TO_ICU_FUNCTIONS +#define RKL_ICU_FUNCTION_APPEND(x) x +#endif // RKL_APPEND_TO_ICU_FUNCTIONS + +#if defined(RKL_DTRACE) && (RKL_DTRACE != 0) +#define _RKL_DTRACE_ENABLED 1 +#endif // defined(RKL_DTRACE) && (RKL_DTRACE != 0) + +// These are internal, non-public tunables. +#define _RKL_FIXED_LENGTH ((NSUInteger)RKL_FIXED_LENGTH) +#define _RKL_STACK_LIMIT ((NSUInteger)RKL_STACK_LIMIT) +#define _RKL_SCRATCH_BUFFERS (5UL) +#if _RKL_SCRATCH_BUFFERS != 5 +#error _RKL_SCRATCH_BUFFERS is not tunable, it must be set to 5. +#endif // _RKL_SCRATCH_BUFFERS != 5 +#define _RKL_PREFETCH_SIZE (64UL) +#define _RKL_DTRACE_REGEXUTF8_SIZE (64UL) + +// A LRU Cache Set holds 4 lines, and the LRU algorithm uses 4 bits per line. +// A LRU Cache Set has a type of RKLLRUCacheSet_t and is 16 bits wide (4 lines * 4 bits per line). +// RKLLRUCacheSet_t must be initialized to a value of 0x0137 in order to work correctly. +typedef uint16_t RKLLRUCacheSet_t; +#define _RKL_LRU_CACHE_SET_INIT ((RKLLRUCacheSet_t)0x0137U) +#define _RKL_LRU_CACHE_SET_WAYS (4UL) +#if _RKL_LRU_CACHE_SET_WAYS != 4 +#error _RKL_LRU_CACHE_SET_WAYS is not tunable, it must be set to 4. +#endif // _RKL_LRU_CACHE_SET_WAYS != 4 + +#define _RKL_REGEX_LRU_CACHE_SETS ((NSUInteger)(RKL_CACHE_SIZE)) +#define _RKL_REGEX_CACHE_LINES ((NSUInteger)((NSUInteger)(_RKL_REGEX_LRU_CACHE_SETS) * (NSUInteger)(_RKL_LRU_CACHE_SET_WAYS))) + +// Regex String Lookaside Cache parameters. +#define _RKL_REGEX_LOOKASIDE_CACHE_BITS (6UL) +#if _RKL_REGEX_LOOKASIDE_CACHE_BITS < 0 +#error _RKL_REGEX_LOOKASIDE_CACHE_BITS must be a non-negative number and is not intended to be user tunable. +#endif // _RKL_REGEX_LOOKASIDE_CACHE_BITS < 0 +#define _RKL_REGEX_LOOKASIDE_CACHE_SIZE (1LU << _RKL_REGEX_LOOKASIDE_CACHE_BITS) +#define _RKL_REGEX_LOOKASIDE_CACHE_MASK ((1LU << _RKL_REGEX_LOOKASIDE_CACHE_BITS) - 1LU) +// RKLLookasideCache_t should be large enough to to hold the maximum number of cached regexes, or (RKL_CACHE_SIZE * _RKL_LRU_CACHE_SET_WAYS). +#if (RKL_CACHE_SIZE * _RKL_LRU_CACHE_SET_WAYS) <= (1 << 8) +typedef uint8_t RKLLookasideCache_t; +#elif (RKL_CACHE_SIZE * _RKL_LRU_CACHE_SET_WAYS) <= (1 << 16) +typedef uint16_t RKLLookasideCache_t; +#else // (RKL_CACHE_SIZE * _RKL_LRU_CACHE_SET_WAYS) > (1 << 16) +typedef uint32_t RKLLookasideCache_t; +#endif // (RKL_CACHE_SIZE * _RKL_LRU_CACHE_SET_WAYS) + +////////////// +#pragma mark - +#pragma mark GCC / Compiler macros + +#if defined (__GNUC__) && (__GNUC__ >= 4) +#define RKL_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__)) +#define RKL_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect)) +#define RKL_PREFETCH(ptr) __builtin_prefetch(ptr) +#define RKL_PREFETCH_UNICHAR(ptr, off) { const char *p = ((const char *)(ptr)) + ((off) * sizeof(UniChar)) + _RKL_PREFETCH_SIZE; RKL_PREFETCH(p); RKL_PREFETCH(p + _RKL_PREFETCH_SIZE); } +#define RKL_HAVE_CLEANUP +#define RKL_CLEANUP(func) RKL_ATTRIBUTES(cleanup(func)) +#else // defined (__GNUC__) && (__GNUC__ >= 4) +#define RKL_ATTRIBUTES(attr, ...) +#define RKL_EXPECTED(cond, expect) (cond) +#define RKL_PREFETCH(ptr) +#define RKL_PREFETCH_UNICHAR(ptr, off) +#define RKL_CLEANUP(func) +#endif // defined (__GNUC__) && (__GNUC__ >= 4) + +#define RKL_STATIC_INLINE static __inline__ RKL_ATTRIBUTES(always_inline) +#define RKL_ALIGNED(arg) RKL_ATTRIBUTES(aligned(arg)) +#define RKL_UNUSED_ARG RKL_ATTRIBUTES(unused) +#define RKL_WARN_UNUSED RKL_ATTRIBUTES(warn_unused_result) +#define RKL_WARN_UNUSED_CONST RKL_ATTRIBUTES(warn_unused_result, const) +#define RKL_WARN_UNUSED_PURE RKL_ATTRIBUTES(warn_unused_result, pure) +#define RKL_WARN_UNUSED_SENTINEL RKL_ATTRIBUTES(warn_unused_result, sentinel) +#define RKL_NONNULL_ARGS(arg, ...) RKL_ATTRIBUTES(nonnull(arg, ##__VA_ARGS__)) +#define RKL_WARN_UNUSED_NONNULL_ARGS(arg, ...) RKL_ATTRIBUTES(warn_unused_result, nonnull(arg, ##__VA_ARGS__)) +#define RKL_WARN_UNUSED_CONST_NONNULL_ARGS(arg, ...) RKL_ATTRIBUTES(warn_unused_result, const, nonnull(arg, ##__VA_ARGS__)) +#define RKL_WARN_UNUSED_PURE_NONNULL_ARGS(arg, ...) RKL_ATTRIBUTES(warn_unused_result, pure, nonnull(arg, ##__VA_ARGS__)) + +#if defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) +#define RKL_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) RKL_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__), alloc_size(as)) +#else // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) +#define RKL_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) RKL_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__)) +#endif // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) + +#ifdef _RKL_DTRACE_ENABLED +#define RKL_UNUSED_DTRACE_ARG +#else // _RKL_DTRACE_ENABLED +#define RKL_UNUSED_DTRACE_ARG RKL_ATTRIBUTES(unused) +#endif // _RKL_DTRACE_ENABLED + +//////////// +#pragma mark - +#pragma mark Assertion macros + +// These macros are nearly identical to their NSCParameterAssert siblings. +// This is required because nearly everything is done while rkl_cacheSpinLock is locked. +// We need to safely unlock before throwing any of these exceptions. +// @try {} @finally {} significantly slows things down so it's not used. + +#define RKLCHardAbortAssert(c) do { int _c=(c); if(RKL_EXPECTED(!_c, 0L)) { NSLog(@"%@:%ld: Invalid parameter not satisfying: %s\n", [NSString stringWithUTF8String:__FILE__], (long)__LINE__, #c); abort(); } } while(0) +#define RKLCAssertDictionary(d, ...) rkl_makeAssertDictionary(__PRETTY_FUNCTION__, __FILE__, __LINE__, (d), ##__VA_ARGS__) +#define RKLCDelayedHardAssert(c, e, g) do { id *_e=(e); int _c=(c); if(RKL_EXPECTED(_e == NULL, 0L) || RKL_EXPECTED(*_e != NULL, 0L)) { goto g; } if(RKL_EXPECTED(!_c, 0L)) { *_e = RKLCAssertDictionary(@"Invalid parameter not satisfying: %s", #c); goto g; } } while(0) + +#ifdef NS_BLOCK_ASSERTIONS +#define RKLCAbortAssert(c) +#define RKLCDelayedAssert(c, e, g) +#define RKL_UNUSED_ASSERTION_ARG RKL_ATTRIBUTES(unused) +#else // NS_BLOCK_ASSERTIONS +#define RKLCAbortAssert(c) RKLCHardAbortAssert(c) +#define RKLCDelayedAssert(c, e, g) RKLCDelayedHardAssert(c, e, g) +#define RKL_UNUSED_ASSERTION_ARG +#endif // NS_BLOCK_ASSERTIONS + +#define RKL_EXCEPTION(e, f, ...) [NSException exceptionWithName:(e) reason:rkl_stringFromClassAndMethod((self), (_cmd), (f), ##__VA_ARGS__) userInfo:NULL] +#define RKL_RAISE_EXCEPTION(e, f, ...) [RKL_EXCEPTION(e, f, ##__VA_ARGS__) raise] + +//////////// +#pragma mark - +#pragma mark Utility functions and macros + +RKL_STATIC_INLINE BOOL NSRangeInsideRange(NSRange cin, NSRange win) RKL_WARN_UNUSED; +RKL_STATIC_INLINE BOOL NSRangeInsideRange(NSRange cin, NSRange win) { return((((cin.location - win.location) <= win.length) && ((NSMaxRange(cin) - win.location) <= win.length)) ? YES : NO); } + +#define NSMakeRange(loc, len) ((NSRange){.location=(NSUInteger)(loc), .length=(NSUInteger)(len)}) +#define CFMakeRange(loc, len) ((CFRange){.location= (CFIndex)(loc), .length= (CFIndex)(len)}) +#define NSNotFoundRange ((NSRange){.location=(NSUInteger)NSNotFound, .length= 0UL}) +#define NSMaxiumRange ((NSRange){.location= 0UL, .length= NSUIntegerMax}) +// These values are used to help tickle improper usage. +#define RKLIllegalRange ((NSRange){.location= NSIntegerMax, .length= NSIntegerMax}) +#define RKLIllegalPointer ((void * RKL_GC_VOLATILE)0xBAD0C0DE) + +//////////// +#pragma mark - +#pragma mark Exported NSString symbols for exception names, error domains, error keys, etc + +NSString * const RKLICURegexException = @"RKLICURegexException"; + +NSString * const RKLICURegexErrorDomain = @"RKLICURegexErrorDomain"; + +NSString * const RKLICURegexEnumerationOptionsErrorKey = @"RKLICURegexEnumerationOptions"; +NSString * const RKLICURegexErrorCodeErrorKey = @"RKLICURegexErrorCode"; +NSString * const RKLICURegexErrorNameErrorKey = @"RKLICURegexErrorName"; +NSString * const RKLICURegexLineErrorKey = @"RKLICURegexLine"; +NSString * const RKLICURegexOffsetErrorKey = @"RKLICURegexOffset"; +NSString * const RKLICURegexPreContextErrorKey = @"RKLICURegexPreContext"; +NSString * const RKLICURegexPostContextErrorKey = @"RKLICURegexPostContext"; +NSString * const RKLICURegexRegexErrorKey = @"RKLICURegexRegex"; +NSString * const RKLICURegexRegexOptionsErrorKey = @"RKLICURegexRegexOptions"; +NSString * const RKLICURegexReplacedCountErrorKey = @"RKLICURegexReplacedCount"; +NSString * const RKLICURegexReplacedStringErrorKey = @"RKLICURegexReplacedString"; +NSString * const RKLICURegexReplacementStringErrorKey = @"RKLICURegexReplacementString"; +NSString * const RKLICURegexSubjectRangeErrorKey = @"RKLICURegexSubjectRange"; +NSString * const RKLICURegexSubjectStringErrorKey = @"RKLICURegexSubjectString"; + +// Used internally by rkl_userInfoDictionary to specify which arguments should be set in the NSError userInfo dictionary. +enum { + RKLUserInfoNone = 0UL, + RKLUserInfoSubjectRange = 1UL << 0, + RKLUserInfoReplacedCount = 1UL << 1, + RKLUserInfoRegexEnumerationOptions = 1UL << 2, +}; +typedef NSUInteger RKLUserInfoOptions; + +//////////// +#pragma mark - +#pragma mark Type / struct definitions + +// In general, the ICU bits and pieces here must exactly match the definition in the ICU sources. + +#define U_STRING_NOT_TERMINATED_WARNING -124 +#define U_ZERO_ERROR 0 +#define U_INDEX_OUTOFBOUNDS_ERROR 8 +#define U_BUFFER_OVERFLOW_ERROR 15 +#define U_PARSE_CONTEXT_LEN 16 + +typedef struct uregex uregex; // Opaque ICU regex type. + +typedef struct UParseError { // This must be exactly the same as the 'real' ICU declaration. + int32_t line; + int32_t offset; + UniChar preContext[U_PARSE_CONTEXT_LEN]; + UniChar postContext[U_PARSE_CONTEXT_LEN]; +} UParseError; + +// For use with GCC's cleanup() __attribute__. +enum { + RKLLockedCacheSpinLock = 1UL << 0, + RKLUnlockedCacheSpinLock = 1UL << 1, +}; + +enum { + RKLSplitOp = 1UL, + RKLReplaceOp = 2UL, + RKLRangeOp = 3UL, + RKLArrayOfStringsOp = 4UL, + RKLArrayOfCapturesOp = 5UL, + RKLCapturesArrayOp = 6UL, + RKLDictionaryOfCapturesOp = 7UL, + RKLArrayOfDictionariesOfCapturesOp = 8UL, + RKLMaskOp = 0xFUL, + RKLReplaceMutable = 1UL << 4, + RKLSubcapturesArray = 1UL << 5, +}; +typedef NSUInteger RKLRegexOp; + +enum { + RKLBlockEnumerationMatchOp = 1UL, + RKLBlockEnumerationReplaceOp = 2UL, +}; +typedef NSUInteger RKLBlockEnumerationOp; + +typedef struct { + RKL_STRONG_REF NSRange * RKL_GC_VOLATILE ranges; + NSRange findInRange, remainingRange; + NSInteger capacity, found, findUpTo, capture, addedSplitRanges; + size_t size, stackUsed; + RKL_STRONG_REF void ** RKL_GC_VOLATILE rangesScratchBuffer; + RKL_STRONG_REF void ** RKL_GC_VOLATILE stringsScratchBuffer; + RKL_STRONG_REF void ** RKL_GC_VOLATILE arraysScratchBuffer; + RKL_STRONG_REF void ** RKL_GC_VOLATILE dictionariesScratchBuffer; + RKL_STRONG_REF void ** RKL_GC_VOLATILE keysScratchBuffer; +} RKLFindAll; + +typedef struct { + CFStringRef string; + CFHashCode hash; + CFIndex length; + RKL_STRONG_REF UniChar * RKL_GC_VOLATILE uniChar; +} RKLBuffer; + +typedef struct { + CFStringRef regexString; + CFHashCode regexHash; + RKLRegexOptions options; + uregex *icu_regex; + NSInteger captureCount; + + CFStringRef setToString; + CFHashCode setToHash; + CFIndex setToLength; + NSUInteger setToIsImmutable:1; + NSUInteger setToNeedsConversion:1; + RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE setToUniChar; + NSRange setToRange, lastFindRange, lastMatchRange; + + RKLBuffer *buffer; +} RKLCachedRegex; + +//////////// +#pragma mark - +#pragma mark Translation unit scope global variables + +static RKLLRUCacheSet_t rkl_lruFixedBufferCacheSet = _RKL_LRU_CACHE_SET_INIT, rkl_lruDynamicBufferCacheSet = _RKL_LRU_CACHE_SET_INIT; +static RKLBuffer rkl_lruDynamicBuffer[_RKL_LRU_CACHE_SET_WAYS]; +static UniChar rkl_lruFixedUniChar[_RKL_LRU_CACHE_SET_WAYS][_RKL_FIXED_LENGTH]; // This is the fixed sized UTF-16 conversion buffer. +static RKLBuffer rkl_lruFixedBuffer[_RKL_LRU_CACHE_SET_WAYS] = {{NULL, 0UL, 0L, &rkl_lruFixedUniChar[0][0]}, {NULL, 0UL, 0L, &rkl_lruFixedUniChar[1][0]}, {NULL, 0UL, 0L, &rkl_lruFixedUniChar[2][0]}, {NULL, 0UL, 0L, &rkl_lruFixedUniChar[3][0]}}; +static RKLCachedRegex rkl_cachedRegexes[_RKL_REGEX_CACHE_LINES]; +#if defined(__GNUC__) && (__GNUC__ == 4) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ == 2) +static RKLCachedRegex * volatile rkl_lastCachedRegex; // XXX This is a work around for what appears to be a optimizer code generation bug in GCC 4.2. +#else +static RKLCachedRegex *rkl_lastCachedRegex; +#endif // defined(__GNUC__) && (__GNUC__ == 4) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ == 2) +static RKLLRUCacheSet_t rkl_cachedRegexCacheSets[_RKL_REGEX_LRU_CACHE_SETS] = { [0 ... (_RKL_REGEX_LRU_CACHE_SETS - 1UL)] = _RKL_LRU_CACHE_SET_INIT }; +static RKLLookasideCache_t rkl_regexLookasideCache[_RKL_REGEX_LOOKASIDE_CACHE_SIZE] RKL_ALIGNED(64); +static OSSpinLock rkl_cacheSpinLock = OS_SPINLOCK_INIT; +static const UniChar rkl_emptyUniCharString[1]; // For safety, icu_regexes are 'set' to this when the string they were searched is cleared. +static RKL_STRONG_REF void * RKL_GC_VOLATILE rkl_scratchBuffer[_RKL_SCRATCH_BUFFERS]; // Used to hold temporary allocations that are allocated via reallocf(). + +//////////// +#pragma mark - +#pragma mark CFArray and CFDictionary call backs + +// These are used when running under manual memory management for the array that rkl_splitArray creates. +// The split strings are created, but not autoreleased. The (immutable) array is created using these callbacks, which skips the CFRetain() call, effectively transferring ownership to the CFArray object. +// For each split string this saves the overhead of an autorelease, then an array retain, then an NSAutoreleasePool release. This is good for a ~30% speed increase. + +static void rkl_CFCallbackRelease(CFAllocatorRef allocator RKL_UNUSED_ARG, const void *ptr) { CFRelease((CFTypeRef)ptr); } +static const CFArrayCallBacks rkl_transferOwnershipArrayCallBacks = { (CFIndex)0L, NULL, rkl_CFCallbackRelease, CFCopyDescription, CFEqual }; +static const CFDictionaryKeyCallBacks rkl_transferOwnershipDictionaryKeyCallBacks = { (CFIndex)0L, NULL, rkl_CFCallbackRelease, CFCopyDescription, CFEqual, CFHash }; +static const CFDictionaryValueCallBacks rkl_transferOwnershipDictionaryValueCallBacks = { (CFIndex)0L, NULL, rkl_CFCallbackRelease, CFCopyDescription, CFEqual }; + +#ifdef __OBJC_GC__ +//////////// +#pragma mark - +#pragma mark Low-level Garbage Collection aware memory/resource allocation utilities +// If compiled with Garbage Collection, we need to be able to do a few things slightly differently. +// The basic premiss is that under GC we use a trampoline function pointer which is set to a _start function to catch the first invocation. +// The _start function checks if GC is running and then overwrites the function pointer with the appropriate routine. Think of it as 'lazy linking'. + +enum { RKLScannedOption = NSScannedOption }; + +// rkl_collectingEnabled uses objc_getClass() to get the NSGarbageCollector class, which doesn't exist on earlier systems. +// This allows for graceful failure should we find ourselves running on an earlier version of the OS without NSGarbageCollector. +static BOOL rkl_collectingEnabled_first (void); +static BOOL rkl_collectingEnabled_yes (void) { return(YES); } +static BOOL rkl_collectingEnabled_no (void) { return(NO); } +static BOOL(*rkl_collectingEnabled) (void) = rkl_collectingEnabled_first; +static BOOL rkl_collectingEnabled_first (void) { + BOOL gcEnabled = ([objc_getClass("NSGarbageCollector") defaultCollector] != NULL) ? YES : NO; + if(gcEnabled == YES) { + // This section of code is required due to what I consider to be a fundamental design flaw in Cocoas GC system. + // Earlier versions of "Garbage Collection Programming Guide" stated that (paraphrased) "all globals are automatically roots". + // Current versions of the guide now include the following warning: + // "You may pass addresses of strong globals or statics into routines expecting pointers to object pointers (such as id* or NSError**) + // only if they have first been assigned to directly, rather than through a pointer dereference." + // This is a surprisingly non-trivial condition to actually meet in practice and is a recipe for impossible to debug race condition bugs. + // We just happen to be very, very, very lucky in the fact that we can initialize our root set before the first use. + NSUInteger x = 0UL; + for(x = 0UL; x < _RKL_SCRATCH_BUFFERS; x++) { rkl_scratchBuffer[x] = NSAllocateCollectable(16UL, 0UL); rkl_scratchBuffer[x] = NULL; } + for(x = 0UL; x < _RKL_LRU_CACHE_SET_WAYS; x++) { rkl_lruDynamicBuffer[x].uniChar = NSAllocateCollectable(16UL, 0UL); rkl_lruDynamicBuffer[x].uniChar = NULL; } + } + return((rkl_collectingEnabled = (gcEnabled == YES) ? rkl_collectingEnabled_yes : rkl_collectingEnabled_no)()); +} + +// rkl_realloc() +static void *rkl_realloc_first (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr, size_t size, NSUInteger flags); +static void *rkl_realloc_std (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr, size_t size, NSUInteger flags RKL_UNUSED_ARG) { return((*ptr = reallocf(*ptr, size))); } +static void *rkl_realloc_gc (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr, size_t size, NSUInteger flags) { return((*ptr = NSReallocateCollectable(*ptr, (NSUInteger)size, flags))); } +static void *(*rkl_realloc) (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr, size_t size, NSUInteger flags) RKL_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(2,1) = rkl_realloc_first; +static void *rkl_realloc_first (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr, size_t size, NSUInteger flags) { if(rkl_collectingEnabled()==YES) { rkl_realloc = rkl_realloc_gc; } else { rkl_realloc = rkl_realloc_std; } return(rkl_realloc(ptr, size, flags)); } + +// rkl_free() +static void * rkl_free_first (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr); +static void * rkl_free_std (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr) { if(*ptr != NULL) { free(*ptr); *ptr = NULL; } return(NULL); } +static void * rkl_free_gc (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr) { if(*ptr != NULL) { *ptr = NULL; } return(NULL); } +static void *(*rkl_free) (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr) RKL_NONNULL_ARGS(1) = rkl_free_first; +static void *rkl_free_first (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr) { if(rkl_collectingEnabled()==YES) { rkl_free = rkl_free_gc; } else { rkl_free = rkl_free_std; } return(rkl_free(ptr)); } + +// rkl_CFAutorelease() +static id rkl_CFAutorelease_first (CFTypeRef obj); +static id rkl_CFAutorelease_std (CFTypeRef obj) { return([(id)obj autorelease]); } +static id rkl_CFAutorelease_gc (CFTypeRef obj) { return(NSMakeCollectable(obj)); } +static id(*rkl_CFAutorelease) (CFTypeRef obj) = rkl_CFAutorelease_first; +static id rkl_CFAutorelease_first (CFTypeRef obj) { return((rkl_CFAutorelease = (rkl_collectingEnabled()==YES) ? rkl_CFAutorelease_gc : rkl_CFAutorelease_std)(obj)); } + +// rkl_CreateStringWithSubstring() +static id rkl_CreateStringWithSubstring_first (id string, NSRange range); +static id rkl_CreateStringWithSubstring_std (id string, NSRange range) { return((id)CFStringCreateWithSubstring(NULL, (CFStringRef)string, CFMakeRange((CFIndex)range.location, (CFIndex)range.length))); } +static id rkl_CreateStringWithSubstring_gc (id string, NSRange range) { return([string substringWithRange:range]); } +static id(*rkl_CreateStringWithSubstring) (id string, NSRange range) RKL_WARN_UNUSED_NONNULL_ARGS(1) = rkl_CreateStringWithSubstring_first; +static id rkl_CreateStringWithSubstring_first (id string, NSRange range) { return((rkl_CreateStringWithSubstring = (rkl_collectingEnabled()==YES) ? rkl_CreateStringWithSubstring_gc : rkl_CreateStringWithSubstring_std)(string, range)); } + +// rkl_ReleaseObject() +static id rkl_ReleaseObject_first (id obj); +static id rkl_ReleaseObject_std (id obj) { CFRelease((CFTypeRef)obj); return(NULL); } +static id rkl_ReleaseObject_gc (id obj RKL_UNUSED_ARG) { return(NULL); } +static id (*rkl_ReleaseObject) (id obj) RKL_NONNULL_ARGS(1) = rkl_ReleaseObject_first; +static id rkl_ReleaseObject_first (id obj) { return((rkl_ReleaseObject = (rkl_collectingEnabled()==YES) ? rkl_ReleaseObject_gc : rkl_ReleaseObject_std)(obj)); } + +// rkl_CreateArrayWithObjects() +static id rkl_CreateArrayWithObjects_first (void **objects, NSUInteger count); +static id rkl_CreateArrayWithObjects_std (void **objects, NSUInteger count) { return((id)CFArrayCreate(NULL, (const void **)objects, (CFIndex)count, &rkl_transferOwnershipArrayCallBacks)); } +static id rkl_CreateArrayWithObjects_gc (void **objects, NSUInteger count) { return([NSArray arrayWithObjects:(const id *)objects count:count]); } +static id(*rkl_CreateArrayWithObjects) (void **objects, NSUInteger count) RKL_WARN_UNUSED_NONNULL_ARGS(1) = rkl_CreateArrayWithObjects_first; +static id rkl_CreateArrayWithObjects_first (void **objects, NSUInteger count) { return((rkl_CreateArrayWithObjects = (rkl_collectingEnabled()==YES) ? rkl_CreateArrayWithObjects_gc : rkl_CreateArrayWithObjects_std)(objects, count)); } + +// rkl_CreateAutoreleasedArray() +static id rkl_CreateAutoreleasedArray_first (void **objects, NSUInteger count); +static id rkl_CreateAutoreleasedArray_std (void **objects, NSUInteger count) { return((id)rkl_CFAutorelease(rkl_CreateArrayWithObjects(objects, count))); } +static id rkl_CreateAutoreleasedArray_gc (void **objects, NSUInteger count) { return( rkl_CreateArrayWithObjects(objects, count) ); } +static id(*rkl_CreateAutoreleasedArray) (void **objects, NSUInteger count) RKL_WARN_UNUSED_NONNULL_ARGS(1) = rkl_CreateAutoreleasedArray_first; +static id rkl_CreateAutoreleasedArray_first (void **objects, NSUInteger count) { return((rkl_CreateAutoreleasedArray = (rkl_collectingEnabled()==YES) ? rkl_CreateAutoreleasedArray_gc : rkl_CreateAutoreleasedArray_std)(objects, count)); } + +#else // __OBJC_GC__ not defined +//////////// +#pragma mark - +#pragma mark Low-level explicit memory/resource allocation utilities + +enum { RKLScannedOption = 0 }; + +#define rkl_collectingEnabled() (NO) + +RKL_STATIC_INLINE void *rkl_realloc (void **ptr, size_t size, NSUInteger flags) RKL_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(2,1); +RKL_STATIC_INLINE void *rkl_free (void **ptr) RKL_NONNULL_ARGS(1); +RKL_STATIC_INLINE id rkl_CFAutorelease (CFTypeRef obj) RKL_WARN_UNUSED_NONNULL_ARGS(1); +RKL_STATIC_INLINE id rkl_CreateAutoreleasedArray (void **objects, NSUInteger count) RKL_WARN_UNUSED_NONNULL_ARGS(1); +RKL_STATIC_INLINE id rkl_CreateArrayWithObjects (void **objects, NSUInteger count) RKL_WARN_UNUSED_NONNULL_ARGS(1); +RKL_STATIC_INLINE id rkl_CreateStringWithSubstring (id string, NSRange range) RKL_WARN_UNUSED_NONNULL_ARGS(1); +RKL_STATIC_INLINE id rkl_ReleaseObject (id obj) RKL_NONNULL_ARGS(1); + +RKL_STATIC_INLINE void *rkl_realloc (void **ptr, size_t size, NSUInteger flags RKL_UNUSED_ARG) { return((*ptr = reallocf(*ptr, size))); } +RKL_STATIC_INLINE void *rkl_free (void **ptr) { if(*ptr != NULL) { free(*ptr); *ptr = NULL; } return(NULL); } +RKL_STATIC_INLINE id rkl_CFAutorelease (CFTypeRef obj) { return([(id)obj autorelease]); } +RKL_STATIC_INLINE id rkl_CreateArrayWithObjects (void **objects, NSUInteger count) { return((id)CFArrayCreate(NULL, (const void **)objects, (CFIndex)count, &rkl_transferOwnershipArrayCallBacks)); } +RKL_STATIC_INLINE id rkl_CreateAutoreleasedArray (void **objects, NSUInteger count) { return(rkl_CFAutorelease(rkl_CreateArrayWithObjects(objects, count))); } +RKL_STATIC_INLINE id rkl_CreateStringWithSubstring (id string, NSRange range) { return((id)CFStringCreateWithSubstring(NULL, (CFStringRef)string, CFMakeRange((CFIndex)range.location, (CFIndex)range.length))); } +RKL_STATIC_INLINE id rkl_ReleaseObject (id obj) { CFRelease((CFTypeRef)obj); return(NULL); } + +#endif // __OBJC_GC__ + +//////////// +#pragma mark - +#pragma mark ICU function prototypes + +// ICU functions. See http://www.icu-project.org/apiref/icu4c/uregex_8h.html Tweaked slightly from the originals, but functionally identical. +const char *RKL_ICU_FUNCTION_APPEND(u_errorName) ( int32_t status) RKL_WARN_UNUSED_PURE; +int32_t RKL_ICU_FUNCTION_APPEND(u_strlen) (const UniChar *s) RKL_WARN_UNUSED_PURE_NONNULL_ARGS(1); +int32_t RKL_ICU_FUNCTION_APPEND(uregex_appendReplacement) ( uregex *regexp, const UniChar *replacementText, int32_t replacementLength, UniChar **destBuf, int32_t *destCapacity, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4,5,6); +int32_t RKL_ICU_FUNCTION_APPEND(uregex_appendTail) ( uregex *regexp, UniChar **destBuf, int32_t *destCapacity, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,3,4); +void RKL_ICU_FUNCTION_APPEND(uregex_close) ( uregex *regexp) RKL_NONNULL_ARGS(1); +int32_t RKL_ICU_FUNCTION_APPEND(uregex_end) ( uregex *regexp, int32_t groupNum, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,3); +BOOL RKL_ICU_FUNCTION_APPEND(uregex_find) ( uregex *regexp, int32_t location, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,3); +BOOL RKL_ICU_FUNCTION_APPEND(uregex_findNext) ( uregex *regexp, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2); +int32_t RKL_ICU_FUNCTION_APPEND(uregex_groupCount) ( uregex *regexp, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2); +uregex *RKL_ICU_FUNCTION_APPEND(uregex_open) (const UniChar *pattern, int32_t patternLength, RKLRegexOptions flags, UParseError *parseError, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,4,5); +void RKL_ICU_FUNCTION_APPEND(uregex_reset) ( uregex *regexp, int32_t newIndex, int32_t *status) RKL_NONNULL_ARGS(1,3); +void RKL_ICU_FUNCTION_APPEND(uregex_setText) ( uregex *regexp, const UniChar *text, int32_t textLength, int32_t *status) RKL_NONNULL_ARGS(1,2,4); +int32_t RKL_ICU_FUNCTION_APPEND(uregex_start) ( uregex *regexp, int32_t groupNum, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,3); +uregex *RKL_ICU_FUNCTION_APPEND(uregex_clone) (const uregex *regexp, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2); + +//////////// +#pragma mark - +#pragma mark RegexKitLite internal, private function prototypes + +// Functions used for managing the 4-way set associative LRU cache and regex string hash lookaside cache. +RKL_STATIC_INLINE NSUInteger rkl_leastRecentlyUsedWayInSet ( NSUInteger cacheSetsCount, const RKLLRUCacheSet_t cacheSetsArray[cacheSetsCount], NSUInteger set) RKL_WARN_UNUSED_NONNULL_ARGS(2); +RKL_STATIC_INLINE void rkl_accessCacheSetWay ( NSUInteger cacheSetsCount, RKLLRUCacheSet_t cacheSetsArray[cacheSetsCount], NSUInteger set, NSUInteger way) RKL_NONNULL_ARGS(2); +RKL_STATIC_INLINE NSUInteger rkl_regexLookasideCacheIndexForPointerAndOptions (const void *ptr, RKLRegexOptions options) RKL_WARN_UNUSED_NONNULL_ARGS(1); +RKL_STATIC_INLINE void rkl_setRegexLookasideCacheToCachedRegexForPointer (const RKLCachedRegex *cachedRegex, const void *ptr) RKL_NONNULL_ARGS(1,2); +RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexFromRegexLookasideCacheForString (const void *ptr, RKLRegexOptions options) RKL_WARN_UNUSED_NONNULL_ARGS(1); +RKL_STATIC_INLINE NSUInteger rkl_makeCacheSetHash ( CFHashCode regexHash, RKLRegexOptions options) RKL_WARN_UNUSED; +RKL_STATIC_INLINE NSUInteger rkl_cacheSetForRegexHashAndOptions ( CFHashCode regexHash, RKLRegexOptions options) RKL_WARN_UNUSED; +RKL_STATIC_INLINE NSUInteger rkl_cacheWayForCachedRegex (const RKLCachedRegex *cachedRegex) RKL_WARN_UNUSED_NONNULL_ARGS(1); +RKL_STATIC_INLINE NSUInteger rkl_cacheSetForCachedRegex (const RKLCachedRegex *cachedRegex) RKL_WARN_UNUSED_NONNULL_ARGS(1); +RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexForCacheSetAndWay ( NSUInteger cacheSet, NSUInteger cacheWay) RKL_WARN_UNUSED; +RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexForRegexHashAndOptionsAndWay ( CFHashCode regexHash, RKLRegexOptions options, NSUInteger cacheWay) RKL_WARN_UNUSED; +RKL_STATIC_INLINE void rkl_updateCachesWithCachedRegex ( RKLCachedRegex *cachedRegex, const void *ptr, int hitOrMiss RKL_UNUSED_DTRACE_ARG, int status RKL_UNUSED_DTRACE_ARG) RKL_NONNULL_ARGS(1,2); +RKL_STATIC_INLINE RKLCachedRegex *rkl_leastRecentlyUsedCachedRegexForRegexHashAndOptions ( CFHashCode regexHash, RKLRegexOptions options) RKL_WARN_UNUSED; + +static RKLCachedRegex *rkl_getCachedRegex (NSString *regexString, RKLRegexOptions options, NSError **error, id *exception) RKL_WARN_UNUSED_NONNULL_ARGS(1,4); +static NSUInteger rkl_setCachedRegexToString (RKLCachedRegex *cachedRegex, const NSRange *range, int32_t *status, id *exception RKL_UNUSED_ASSERTION_ARG) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,3,4); +static RKLCachedRegex *rkl_getCachedRegexSetToString (NSString *regexString, RKLRegexOptions options, NSString *matchString, NSUInteger *matchLengthPtr, NSRange *matchRange, NSError **error, id *exception, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,3,4,5,7,8); +static id rkl_performDictionaryVarArgsOp(id self, SEL _cmd, RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, NSInteger capture, id matchString, NSRange *matchRange, NSString *replacementString, NSError **error, void *result, id firstKey, va_list varArgsList) RKL_NONNULL_ARGS(1,2); +static id rkl_performRegexOp (id self, SEL _cmd, RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, NSInteger capture, id matchString, NSRange *matchRange, NSString *replacementString, NSError **error, void *result, NSUInteger captureKeysCount, id captureKeys[captureKeysCount], const int captureKeyIndexes[captureKeysCount]) RKL_NONNULL_ARGS(1,2); +static void rkl_handleDelayedAssert (id self, SEL _cmd, id exception) RKL_NONNULL_ARGS(3); + +static NSUInteger rkl_search (RKLCachedRegex *cachedRegex, NSRange *searchRange, NSUInteger updateSearchRange, id *exception RKL_UNUSED_ASSERTION_ARG, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4,5); + +static BOOL rkl_findRanges (RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, id *exception, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,3,4,5); +static NSUInteger rkl_growFindRanges (RKLCachedRegex *cachedRegex, NSUInteger lastLocation, RKLFindAll *findAll, id *exception RKL_UNUSED_ASSERTION_ARG) RKL_WARN_UNUSED_NONNULL_ARGS(1,3,4); +static NSArray *rkl_makeArray (RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, id *exception RKL_UNUSED_ASSERTION_ARG) RKL_WARN_UNUSED_NONNULL_ARGS(1,3,4); +static id rkl_makeDictionary (RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, NSUInteger captureKeysCount, id captureKeys[captureKeysCount], const int captureKeyIndexes[captureKeysCount], id *exception RKL_UNUSED_ASSERTION_ARG) RKL_WARN_UNUSED_NONNULL_ARGS(1,3,5,6); + +static NSString *rkl_replaceString (RKLCachedRegex *cachedRegex, id searchString, NSUInteger searchU16Length, NSString *replacementString, NSUInteger replacementU16Length, NSInteger *replacedCount, NSUInteger replaceMutable, id *exception, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4,8,9); +static int32_t rkl_replaceAll (RKLCachedRegex *cachedRegex, RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE replacementUniChar, int32_t replacementU16Length, UniChar *replacedUniChar, int32_t replacedU16Capacity, NSInteger *replacedCount, int32_t *needU16Capacity, id *exception RKL_UNUSED_ASSERTION_ARG, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4,6,7,8,9); + +static NSUInteger rkl_isRegexValid (id self, SEL _cmd, NSString *regex, RKLRegexOptions options, NSInteger *captureCountPtr, NSError **error) RKL_NONNULL_ARGS(1,2); + +static void rkl_clearStringCache (void); +static void rkl_clearBuffer (RKLBuffer *buffer, NSUInteger freeDynamicBuffer) RKL_NONNULL_ARGS(1); +static void rkl_clearCachedRegex (RKLCachedRegex *cachedRegex) RKL_NONNULL_ARGS(1); +static void rkl_clearCachedRegexSetTo (RKLCachedRegex *cachedRegex) RKL_NONNULL_ARGS(1); + +static NSDictionary *rkl_userInfoDictionary (RKLUserInfoOptions userInfoOptions, NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status, NSString *matchString, NSRange matchRange, NSString *replacementString, NSString *replacedString, NSInteger replacedCount, RKLRegexEnumerationOptions enumerationOptions, ...) RKL_WARN_UNUSED_SENTINEL; +static NSError *rkl_makeNSError (RKLUserInfoOptions userInfoOptions, NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status, NSString *matchString, NSRange matchRange, NSString *replacementString, NSString *replacedString, NSInteger replacedCount, RKLRegexEnumerationOptions enumerationOptions, NSString *errorDescription) RKL_WARN_UNUSED; + +static NSException *rkl_NSExceptionForRegex (NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status) RKL_WARN_UNUSED_NONNULL_ARGS(1); +static NSDictionary *rkl_makeAssertDictionary (const char *function, const char *file, int line, NSString *format, ...) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4); +static NSString *rkl_stringFromClassAndMethod (id object, SEL selector, NSString *format, ...) RKL_WARN_UNUSED_NONNULL_ARGS(3); + +RKL_STATIC_INLINE int32_t rkl_getRangeForCapture(RKLCachedRegex *cr, int32_t *s, int32_t c, NSRange *r) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4); +RKL_STATIC_INLINE int32_t rkl_getRangeForCapture(RKLCachedRegex *cr, int32_t *s, int32_t c, NSRange *r) { uregex *re = cr->icu_regex; int32_t start = RKL_ICU_FUNCTION_APPEND(uregex_start)(re, c, s); if(RKL_EXPECTED((*s > U_ZERO_ERROR), 0L) || (start == -1)) { *r = NSNotFoundRange; } else { r->location = (NSUInteger)start; r->length = (NSUInteger)RKL_ICU_FUNCTION_APPEND(uregex_end)(re, c, s) - r->location; r->location += cr->setToRange.location; } return(*s); } + +RKL_STATIC_INLINE RKLFindAll rkl_makeFindAll(RKL_STRONG_REF NSRange * RKL_GC_VOLATILE r, NSRange fir, NSInteger c, size_t s, size_t su, RKL_STRONG_REF void ** RKL_GC_VOLATILE rsb, RKL_STRONG_REF void ** RKL_GC_VOLATILE ssb, RKL_STRONG_REF void ** RKL_GC_VOLATILE asb, RKL_STRONG_REF void ** RKL_GC_VOLATILE dsb, RKL_STRONG_REF void ** RKL_GC_VOLATILE ksb, NSInteger f, NSInteger cap, NSInteger fut) RKL_WARN_UNUSED_CONST; +RKL_STATIC_INLINE RKLFindAll rkl_makeFindAll(RKL_STRONG_REF NSRange * RKL_GC_VOLATILE r, NSRange fir, NSInteger c, size_t s, size_t su, RKL_STRONG_REF void ** RKL_GC_VOLATILE rsb, RKL_STRONG_REF void ** RKL_GC_VOLATILE ssb, RKL_STRONG_REF void ** RKL_GC_VOLATILE asb, RKL_STRONG_REF void ** RKL_GC_VOLATILE dsb, RKL_STRONG_REF void ** RKL_GC_VOLATILE ksb, NSInteger f, NSInteger cap, NSInteger fut) { return(((RKLFindAll){ .ranges=r, .findInRange=fir, .remainingRange=fir, .capacity=c, .found=f, .findUpTo=fut, .capture=cap, .addedSplitRanges=0L, .size=s, .stackUsed=su, .rangesScratchBuffer=rsb, .stringsScratchBuffer=ssb, .arraysScratchBuffer=asb, .dictionariesScratchBuffer=dsb, .keysScratchBuffer=ksb})); } + +//////////// +#pragma mark - +#pragma mark RKL_FAST_MUTABLE_CHECK implementation + +#ifdef RKL_FAST_MUTABLE_CHECK +// We use a trampoline function pointer to check at run time if the function __CFStringIsMutable is available. +// If it is, the trampoline function pointer is replaced with the address of that function. +// Otherwise, we assume the worst case that every string is mutable. +// This hopefully helps to protect us since we're using an undocumented, non-public API call. +// We will keep on working if it ever does go away, just with a bit less performance due to the overhead of mutable checks. + +static BOOL rkl_CFStringIsMutable_first (CFStringRef str); +static BOOL rkl_CFStringIsMutable_yes (CFStringRef str RKL_UNUSED_ARG) { return(YES); } +static BOOL(*rkl_CFStringIsMutable) (CFStringRef str) = rkl_CFStringIsMutable_first; +static BOOL rkl_CFStringIsMutable_first (CFStringRef str) { if((rkl_CFStringIsMutable = (BOOL(*)(CFStringRef))dlsym(RTLD_DEFAULT, "__CFStringIsMutable")) == NULL) { rkl_CFStringIsMutable = rkl_CFStringIsMutable_yes; } return(rkl_CFStringIsMutable(str)); } +#else // RKL_FAST_MUTABLE_CHECK is not defined. Assume that all strings are potentially mutable. +#define rkl_CFStringIsMutable(s) (YES) +#endif // RKL_FAST_MUTABLE_CHECK + +//////////// +#pragma mark - +#pragma mark iPhone / iPod touch low memory notification handler + +#if defined(RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS) && (RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS == 1) + +// The next few lines are specifically for the iPhone to catch low memory conditions. +// The basic idea is that rkl_RegisterForLowMemoryNotifications() is set to be run once by the linker at load time via __attribute((constructor)). +// rkl_RegisterForLowMemoryNotifications() tries to find the iPhone low memory notification symbol. If it can find it, +// it registers with the default NSNotificationCenter to call the RKLLowMemoryWarningObserver class method +lowMemoryWarning:. +// rkl_RegisterForLowMemoryNotifications() uses an atomic compare and swap to guarantee that it initializes exactly once. +// +lowMemoryWarning tries to acquire the cache lock. If it gets the lock, it clears the cache. If it can't, it calls performSelector: +// with a delay of half a second to try again. This will hopefully prevent any deadlocks, such as a RegexKitLite request for +// memory triggering a notification while the lock is held. + +static void rkl_RegisterForLowMemoryNotifications(void) RKL_ATTRIBUTES(used); + +@interface RKLLowMemoryWarningObserver : NSObject +(void)lowMemoryWarning:(id)notification; @end +@implementation RKLLowMemoryWarningObserver ++(void)lowMemoryWarning:(id)notification { + if(OSSpinLockTry(&rkl_cacheSpinLock)) { rkl_clearStringCache(); OSSpinLockUnlock(&rkl_cacheSpinLock); } + else { [[RKLLowMemoryWarningObserver class] performSelector:@selector(lowMemoryWarning:) withObject:notification afterDelay:(NSTimeInterval)0.1]; } +} +@end + +static volatile int rkl_HaveRegisteredForLowMemoryNotifications = 0; + +__attribute__((constructor)) static void rkl_RegisterForLowMemoryNotifications(void) { + _Bool didSwap = false; + void **memoryWarningNotification = NULL; + + while((rkl_HaveRegisteredForLowMemoryNotifications == 0) && ((didSwap = OSAtomicCompareAndSwapIntBarrier(0, 1, &rkl_HaveRegisteredForLowMemoryNotifications)) == false)) { /* Allows for spurious CAS failures. */ } + if(didSwap == true) { + if((memoryWarningNotification = (void **)dlsym(RTLD_DEFAULT, "UIApplicationDidReceiveMemoryWarningNotification")) != NULL) { + [[NSNotificationCenter defaultCenter] addObserver:[RKLLowMemoryWarningObserver class] selector:@selector(lowMemoryWarning:) name:(NSString *)*memoryWarningNotification object:NULL]; + } + } +} + +#endif // defined(RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS) && (RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS == 1) + +//////////// +#pragma mark - +#pragma mark DTrace functionality + +#ifdef _RKL_DTRACE_ENABLED + +// compiledRegexCache(unsigned long eventID, const char *regexUTF8, int options, int captures, int hitMiss, int icuStatusCode, const char *icuErrorMessage, double *hitRate); +// utf16ConversionCache(unsigned long eventID, unsigned int lookupResultFlags, double *hitRate, const void *string, unsigned long NSRange.location, unsigned long NSRange.length, long length); + +/* +provider RegexKitLite { + probe compiledRegexCache(unsigned long, const char *, unsigned int, int, int, int, const char *, double *); + probe utf16ConversionCache(unsigned long, unsigned int, double *, const void *, unsigned long, unsigned long, long); +}; + +#pragma D attributes Unstable/Unstable/Common provider RegexKitLite provider +#pragma D attributes Private/Private/Common provider RegexKitLite module +#pragma D attributes Private/Private/Common provider RegexKitLite function +#pragma D attributes Unstable/Unstable/Common provider RegexKitLite name +#pragma D attributes Unstable/Unstable/Common provider RegexKitLite args +*/ + +#define REGEXKITLITE_STABILITY "___dtrace_stability$RegexKitLite$v1$4_4_5_1_1_5_1_1_5_4_4_5_4_4_5" +#define REGEXKITLITE_TYPEDEFS "___dtrace_typedefs$RegexKitLite$v1" +#define REGEXKITLITE_COMPILEDREGEXCACHE(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) { __asm__ volatile(".reference " REGEXKITLITE_TYPEDEFS); __dtrace_probe$RegexKitLite$compiledRegexCache$v1$756e7369676e6564206c6f6e67$63686172202a$756e7369676e656420696e74$696e74$696e74$696e74$63686172202a$646f75626c65202a(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); __asm__ volatile(".reference " REGEXKITLITE_STABILITY); } +#define REGEXKITLITE_COMPILEDREGEXCACHE_ENABLED() __dtrace_isenabled$RegexKitLite$compiledRegexCache$v1() +#define REGEXKITLITE_CONVERTEDSTRINGU16CACHE(arg0, arg1, arg2, arg3, arg4, arg5, arg6) { __asm__ volatile(".reference " REGEXKITLITE_TYPEDEFS); __dtrace_probe$RegexKitLite$utf16ConversionCache$v1$756e7369676e6564206c6f6e67$756e7369676e656420696e74$646f75626c65202a$766f6964202a$756e7369676e6564206c6f6e67$756e7369676e6564206c6f6e67$6c6f6e67(arg0, arg1, arg2, arg3, arg4, arg5, arg6); __asm__ volatile(".reference " REGEXKITLITE_STABILITY); } +#define REGEXKITLITE_CONVERTEDSTRINGU16CACHE_ENABLED() __dtrace_isenabled$RegexKitLite$utf16ConversionCache$v1() + +extern void __dtrace_probe$RegexKitLite$compiledRegexCache$v1$756e7369676e6564206c6f6e67$63686172202a$756e7369676e656420696e74$696e74$696e74$696e74$63686172202a$646f75626c65202a(unsigned long, const char *, unsigned int, int, int, int, const char *, double *); +extern int __dtrace_isenabled$RegexKitLite$compiledRegexCache$v1(void); +extern void __dtrace_probe$RegexKitLite$utf16ConversionCache$v1$756e7369676e6564206c6f6e67$756e7369676e656420696e74$646f75626c65202a$766f6964202a$756e7369676e6564206c6f6e67$756e7369676e6564206c6f6e67$6c6f6e67(unsigned long, unsigned int, double *, const void *, unsigned long, unsigned long, long); +extern int __dtrace_isenabled$RegexKitLite$utf16ConversionCache$v1(void); + +//////////////////////////// + +enum { + RKLCacheHitLookupFlag = 1 << 0, + RKLConversionRequiredLookupFlag = 1 << 1, + RKLSetTextLookupFlag = 1 << 2, + RKLDynamicBufferLookupFlag = 1 << 3, + RKLErrorLookupFlag = 1 << 4, + RKLEnumerationBufferLookupFlag = 1 << 5, +}; + +#define rkl_dtrace_addLookupFlag(a,b) do { a |= (unsigned int)(b); } while(0) + +static char rkl_dtrace_regexUTF8[_RKL_REGEX_CACHE_LINES + 1UL][_RKL_DTRACE_REGEXUTF8_SIZE]; +static NSUInteger rkl_dtrace_eventID, rkl_dtrace_compiledCacheLookups, rkl_dtrace_compiledCacheHits, rkl_dtrace_conversionBufferLookups, rkl_dtrace_conversionBufferHits; + +#define rkl_dtrace_incrementEventID() do { rkl_dtrace_eventID++; } while(0) +#define rkl_dtrace_incrementAndGetEventID(v) do { rkl_dtrace_eventID++; v = rkl_dtrace_eventID; } while(0) +#define rkl_dtrace_compiledRegexCache(a0, a1, a2, a3, a4, a5) do { int _a3 = (a3); rkl_dtrace_compiledCacheLookups++; if(_a3 == 1) { rkl_dtrace_compiledCacheHits++; } if(RKL_EXPECTED(REGEXKITLITE_COMPILEDREGEXCACHE_ENABLED(), 0L)) { double hitRate = 0.0; if(rkl_dtrace_compiledCacheLookups > 0UL) { hitRate = ((double)rkl_dtrace_compiledCacheHits / (double)rkl_dtrace_compiledCacheLookups) * 100.0; } REGEXKITLITE_COMPILEDREGEXCACHE(rkl_dtrace_eventID, a0, a1, a2, _a3, a4, a5, &hitRate); } } while(0) +#define rkl_dtrace_utf16ConversionCache(a0, a1, a2, a3, a4) do { unsigned int _a0 = (a0); if((_a0 & RKLConversionRequiredLookupFlag) != 0U) { rkl_dtrace_conversionBufferLookups++; if((_a0 & RKLCacheHitLookupFlag) != 0U) { rkl_dtrace_conversionBufferHits++; } } if(RKL_EXPECTED(REGEXKITLITE_CONVERTEDSTRINGU16CACHE_ENABLED(), 0L)) { double hitRate = 0.0; if(rkl_dtrace_conversionBufferLookups > 0UL) { hitRate = ((double)rkl_dtrace_conversionBufferHits / (double)rkl_dtrace_conversionBufferLookups) * 100.0; } REGEXKITLITE_CONVERTEDSTRINGU16CACHE(rkl_dtrace_eventID, _a0, &hitRate, a1, a2, a3, a4); } } while(0) +#define rkl_dtrace_utf16ConversionCacheWithEventID(c0, a0, a1, a2, a3, a4) do { unsigned int _a0 = (a0); if((_a0 & RKLConversionRequiredLookupFlag) != 0U) { rkl_dtrace_conversionBufferLookups++; if((_a0 & RKLCacheHitLookupFlag) != 0U) { rkl_dtrace_conversionBufferHits++; } } if(RKL_EXPECTED(REGEXKITLITE_CONVERTEDSTRINGU16CACHE_ENABLED(), 0L)) { double hitRate = 0.0; if(rkl_dtrace_conversionBufferLookups > 0UL) { hitRate = ((double)rkl_dtrace_conversionBufferHits / (double)rkl_dtrace_conversionBufferLookups) * 100.0; } REGEXKITLITE_CONVERTEDSTRINGU16CACHE(c0, _a0, &hitRate, a1, a2, a3, a4); } } while(0) + + +// \342\200\246 == UTF8 for HORIZONTAL ELLIPSIS, aka triple dots '...' +#define RKL_UTF8_ELLIPSE "\342\200\246" + +// rkl_dtrace_getRegexUTF8 will copy the str argument to utf8Buffer using UTF8 as the string encoding. +// If the utf8 encoding would take up more bytes than the utf8Buffers length, then the unicode character 'HORIZONTAL ELLIPSIS' ('...') is appended to indicate truncation occurred. +static void rkl_dtrace_getRegexUTF8(CFStringRef str, char *utf8Buffer) RKL_NONNULL_ARGS(2); +static void rkl_dtrace_getRegexUTF8(CFStringRef str, char *utf8Buffer) { + if((str == NULL) || (utf8Buffer == NULL)) { return; } + CFIndex maxLength = ((CFIndex)_RKL_DTRACE_REGEXUTF8_SIZE - 2L), maxBytes = (maxLength - (CFIndex)sizeof(RKL_UTF8_ELLIPSE) - 1L), stringU16Length = CFStringGetLength(str), usedBytes = 0L; + CFStringGetBytes(str, CFMakeRange(0L, ((stringU16Length < maxLength) ? stringU16Length : maxLength)), kCFStringEncodingUTF8, (UInt8)'?', (Boolean)0, (UInt8 *)utf8Buffer, maxBytes, &usedBytes); + if(usedBytes == maxBytes) { strncpy(utf8Buffer + usedBytes, RKL_UTF8_ELLIPSE, ((size_t)_RKL_DTRACE_REGEXUTF8_SIZE - (size_t)usedBytes) - 2UL); } else { utf8Buffer[usedBytes] = (char)0; } +} + +#else // _RKL_DTRACE_ENABLED + +#define rkl_dtrace_incrementEventID() +#define rkl_dtrace_incrementAndGetEventID(v) +#define rkl_dtrace_compiledRegexCache(a0, a1, a2, a3, a4, a5) +#define rkl_dtrace_utf16ConversionCache(a0, a1, a2, a3, a4) +#define rkl_dtrace_utf16ConversionCacheWithEventID(c0, a0, a1, a2, a3, a4) +#define rkl_dtrace_getRegexUTF8(str, buf) +#define rkl_dtrace_addLookupFlag(a,b) + +#endif // _RKL_DTRACE_ENABLED + +//////////// +#pragma mark - +#pragma mark RegexKitLite low-level internal functions +#pragma mark - + +// The 4-way set associative LRU logic comes from Henry S. Warren Jr.'s Hacker's Delight, "revisions", 7-7 An LRU Algorithm: +// http://www.hackersdelight.org/revisions.pdf +// The functions rkl_leastRecentlyUsedWayInSet() and rkl_accessCacheSetWay() implement the cache functionality and are used +// from a number of different places that need to perform caching (i.e., cached regex, cached UTF16 conversions, etc) + +#pragma mark 4-way set associative LRU functions + +RKL_STATIC_INLINE NSUInteger rkl_leastRecentlyUsedWayInSet(NSUInteger cacheSetsCount, const RKLLRUCacheSet_t cacheSetsArray[cacheSetsCount], NSUInteger set) { + RKLCAbortAssert((cacheSetsArray != NULL) && ((NSInteger)cacheSetsCount > 0L) && (set < cacheSetsCount) && ((cacheSetsArray == rkl_cachedRegexCacheSets) ? set < _RKL_REGEX_LRU_CACHE_SETS : 1) && (((sizeof(unsigned int) - sizeof(RKLLRUCacheSet_t)) * 8) < (sizeof(unsigned int) * 8))); + unsigned int cacheSet = (((unsigned int)cacheSetsArray[set]) << ((sizeof(unsigned int) - sizeof(RKLLRUCacheSet_t)) * 8)); // __builtin_clz takes an 'unsigned int' argument. The rest is to ensure bit alignment regardless of 32/64/whatever. + NSUInteger leastRecentlyUsed = ((NSUInteger)(3LU - (NSUInteger)((__builtin_clz((~(((cacheSet & 0x77777777U) + 0x77777777U) | cacheSet | 0x77777777U))) ) >> 2))); + RKLCAbortAssert(leastRecentlyUsed < _RKL_LRU_CACHE_SET_WAYS); + return(leastRecentlyUsed); +} + +RKL_STATIC_INLINE void rkl_accessCacheSetWay(NSUInteger cacheSetsCount, RKLLRUCacheSet_t cacheSetsArray[cacheSetsCount], NSUInteger cacheSet, NSUInteger cacheWay) { + RKLCAbortAssert((cacheSetsArray != NULL) && ((NSInteger)cacheSetsCount > 0L) && (cacheSet < cacheSetsCount) && (cacheWay < _RKL_LRU_CACHE_SET_WAYS) && ((cacheSetsArray == rkl_cachedRegexCacheSets) ? cacheSet < _RKL_REGEX_LRU_CACHE_SETS : 1)); + cacheSetsArray[cacheSet] = (RKLLRUCacheSet_t)(((cacheSetsArray[cacheSet] & (RKLLRUCacheSet_t)0xFFFFU) | (((RKLLRUCacheSet_t)0xFU) << (cacheWay * 4U))) & (~(((RKLLRUCacheSet_t)0x1111U) << (3U - cacheWay)))); +} + +#pragma mark Common, macro'ish compiled regular expression cache logic + +// These functions consolidate bits and pieces of code used to maintain, update, and access the 4-way set associative LRU cache and Regex Lookaside Cache. +RKL_STATIC_INLINE NSUInteger rkl_regexLookasideCacheIndexForPointerAndOptions (const void *ptr, RKLRegexOptions options) { return(((((NSUInteger)(ptr)) >> 4) + options + (options >> 4)) & _RKL_REGEX_LOOKASIDE_CACHE_MASK); } +RKL_STATIC_INLINE void rkl_setRegexLookasideCacheToCachedRegexForPointer (const RKLCachedRegex *cachedRegex, const void *ptr) { rkl_regexLookasideCache[rkl_regexLookasideCacheIndexForPointerAndOptions(ptr, cachedRegex->options)] = (cachedRegex - rkl_cachedRegexes); } +RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexFromRegexLookasideCacheForString (const void *ptr, RKLRegexOptions options) { return(&rkl_cachedRegexes[rkl_regexLookasideCache[rkl_regexLookasideCacheIndexForPointerAndOptions(ptr, options)]]); } +RKL_STATIC_INLINE NSUInteger rkl_makeCacheSetHash ( CFHashCode regexHash, RKLRegexOptions options) { return((NSUInteger)regexHash ^ (NSUInteger)options); } +RKL_STATIC_INLINE NSUInteger rkl_cacheSetForRegexHashAndOptions ( CFHashCode regexHash, RKLRegexOptions options) { return((rkl_makeCacheSetHash(regexHash, options) % _RKL_REGEX_LRU_CACHE_SETS)); } +RKL_STATIC_INLINE NSUInteger rkl_cacheWayForCachedRegex (const RKLCachedRegex *cachedRegex) { return((cachedRegex - rkl_cachedRegexes) % _RKL_LRU_CACHE_SET_WAYS); } +RKL_STATIC_INLINE NSUInteger rkl_cacheSetForCachedRegex (const RKLCachedRegex *cachedRegex) { return(rkl_cacheSetForRegexHashAndOptions(cachedRegex->regexHash, cachedRegex->options)); } +RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexForCacheSetAndWay ( NSUInteger cacheSet, NSUInteger cacheWay) { return(&rkl_cachedRegexes[((cacheSet * _RKL_LRU_CACHE_SET_WAYS) + cacheWay)]); } +RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexForRegexHashAndOptionsAndWay ( CFHashCode regexHash, RKLRegexOptions options, NSUInteger cacheWay) { return(rkl_cachedRegexForCacheSetAndWay(rkl_cacheSetForRegexHashAndOptions(regexHash, options), cacheWay)); } + +RKL_STATIC_INLINE void rkl_updateCachesWithCachedRegex(RKLCachedRegex *cachedRegex, const void *ptr, int hitOrMiss RKL_UNUSED_DTRACE_ARG, int status RKL_UNUSED_DTRACE_ARG) { + rkl_lastCachedRegex = cachedRegex; + rkl_setRegexLookasideCacheToCachedRegexForPointer(cachedRegex, ptr); + rkl_accessCacheSetWay(_RKL_REGEX_LRU_CACHE_SETS, rkl_cachedRegexCacheSets, rkl_cacheSetForCachedRegex(cachedRegex), rkl_cacheWayForCachedRegex(cachedRegex)); // Set the matching line as the most recently used. + rkl_dtrace_compiledRegexCache(&rkl_dtrace_regexUTF8[(cachedRegex - rkl_cachedRegexes)][0], cachedRegex->options, (int)cachedRegex->captureCount, hitOrMiss, status, NULL); +} + +RKL_STATIC_INLINE RKLCachedRegex *rkl_leastRecentlyUsedCachedRegexForRegexHashAndOptions(CFHashCode regexHash, RKLRegexOptions options) { + NSUInteger cacheSet = rkl_cacheSetForRegexHashAndOptions(regexHash, options); + return(rkl_cachedRegexForCacheSetAndWay(cacheSet, rkl_leastRecentlyUsedWayInSet(_RKL_REGEX_LRU_CACHE_SETS, rkl_cachedRegexCacheSets, cacheSet))); +} + +#pragma mark Regular expression lookup function + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// IMPORTANT! Should only be called with rkl_cacheSpinLock already locked! +// ---------- + +static RKLCachedRegex *rkl_getCachedRegex(NSString *regexString, RKLRegexOptions options, NSError **error, id *exception) { + // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv + // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! + // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv + + RKLCachedRegex *cachedRegex = NULL; + CFHashCode regexHash = 0UL; + int32_t status = 0; + + RKLCDelayedAssert((rkl_cacheSpinLock != (OSSpinLock)0) && (regexString != NULL), exception, exitNow); + + // Fast path the common case where this regex is exactly the same one used last time. + // The pointer equality test is valid under these circumstances since the cachedRegex->regexString is an immutable copy. + // If the regexString argument is mutable, this test will fail, and we'll use the the slow path cache check below. + if(RKL_EXPECTED(rkl_lastCachedRegex != NULL, 1L) && RKL_EXPECTED(rkl_lastCachedRegex->regexString == (CFStringRef)regexString, 1L) && RKL_EXPECTED(rkl_lastCachedRegex->options == options, 1L) && RKL_EXPECTED(rkl_lastCachedRegex->icu_regex != NULL, 1L)) { + rkl_dtrace_compiledRegexCache(&rkl_dtrace_regexUTF8[(rkl_lastCachedRegex - rkl_cachedRegexes)][0], rkl_lastCachedRegex->options, (int)rkl_lastCachedRegex->captureCount, 1, 0, NULL); + return(rkl_lastCachedRegex); + } + + rkl_lastCachedRegex = NULL; // Make sure that rkl_lastCachedRegex is NULL in case there is some kind of error. + cachedRegex = rkl_cachedRegexFromRegexLookasideCacheForString(regexString, options); // Check the Regex Lookaside Cache to see if we can quickly find the correct Cached Regex for this regexString pointer + options. + if((RKL_EXPECTED(cachedRegex->regexString == (CFStringRef)regexString, 1L) || (RKL_EXPECTED(cachedRegex->regexString != NULL, 1L) && RKL_EXPECTED(CFEqual((CFTypeRef)regexString, (CFTypeRef)cachedRegex->regexString) == YES, 1L))) && RKL_EXPECTED(cachedRegex->options == options, 1L) && RKL_EXPECTED(cachedRegex->icu_regex != NULL, 1L)) { goto foundMatch; } // There was a Regex Lookaside Cache hit, jump to foundMatch: to quickly return the result. A Regex Lookaside Cache hit allows us to bypass calling CFHash(), which is a decent performance win. + else { cachedRegex = NULL; regexHash = CFHash((CFTypeRef)regexString); } // Regex Lookaside Cache miss. We need to call CFHash() to determine the cache set for this regex. + + NSInteger cacheWay = 0L; // Check each way of the set that this regex belongs to. + for(cacheWay = ((NSInteger)_RKL_LRU_CACHE_SET_WAYS - 1L); cacheWay > 0L; cacheWay--) { // Checking the ways in reverse (3, 2, 1, 0) finds a match "sooner" on average. + cachedRegex = rkl_cachedRegexForRegexHashAndOptionsAndWay(regexHash, options, (NSUInteger)cacheWay); + // Return the cached entry if it's a match. If regexString is mutable, the pointer equality test will fail, and CFEqual() is used to determine true equality with the immutable cachedRegex copy. CFEqual() performs a slow character by character check. + if(RKL_EXPECTED(cachedRegex->regexHash == regexHash, 0UL) && ((cachedRegex->regexString == (CFStringRef)regexString) || (RKL_EXPECTED(cachedRegex->regexString != NULL, 1L) && RKL_EXPECTED(CFEqual((CFTypeRef)regexString, (CFTypeRef)cachedRegex->regexString) == YES, 1L))) && RKL_EXPECTED(cachedRegex->options == options, 1L) && RKL_EXPECTED(cachedRegex->icu_regex != NULL, 1L)) { + foundMatch: // Control can transfer here (from above) via a Regex Lookaside Cache hit. + rkl_updateCachesWithCachedRegex(cachedRegex, regexString, 1, 0); + return(cachedRegex); + } + } + + // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! + // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + // Code below this point is not as sensitive to speed since compiling a regular expression is an extremely expensive operation. + // The regex was not found in the cache. Get the cached regex for the least recently used line in the set, then clear the cached regex and create a new ICU regex in its place. + cachedRegex = rkl_leastRecentlyUsedCachedRegexForRegexHashAndOptions(regexHash, options); + rkl_clearCachedRegex(cachedRegex); + + if(RKL_EXPECTED((cachedRegex->regexString = CFStringCreateCopy(NULL, (CFStringRef)regexString)) == NULL, 0L)) { goto exitNow; } ; // Get a cheap immutable copy. + rkl_dtrace_getRegexUTF8(cachedRegex->regexString, &rkl_dtrace_regexUTF8[(cachedRegex - rkl_cachedRegexes)][0]); + cachedRegex->regexHash = regexHash; + cachedRegex->options = options; + + CFIndex regexStringU16Length = CFStringGetLength(cachedRegex->regexString); // In UTF16 code units. + UParseError parseError = (UParseError){-1, -1, {0}, {0}}; + RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE regexUniChar = NULL; + + if(RKL_EXPECTED(regexStringU16Length >= (CFIndex)INT_MAX, 0L)) { *exception = [NSException exceptionWithName:NSRangeException reason:@"Regex string length exceeds INT_MAX" userInfo:NULL]; goto exitNow; } + + // Try to quickly obtain regexString in UTF16 format. + if((regexUniChar = CFStringGetCharactersPtr(cachedRegex->regexString)) == NULL) { // We didn't get the UTF16 pointer quickly and need to perform a full conversion in a temp buffer. + RKL_STRONG_REF UniChar * RKL_GC_VOLATILE uniCharBuffer = NULL; + if(((size_t)regexStringU16Length * sizeof(UniChar)) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((uniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)alloca( (size_t)regexStringU16Length * sizeof(UniChar) )) == NULL, 0L)) { goto exitNow; } } // Try to use the stack. + else { if(RKL_EXPECTED((uniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc(&rkl_scratchBuffer[0], (size_t)regexStringU16Length * sizeof(UniChar), 0UL)) == NULL, 0L)) { goto exitNow; } } // Otherwise use the heap. + CFStringGetCharacters(cachedRegex->regexString, CFMakeRange(0L, regexStringU16Length), uniCharBuffer); // Convert regexString to UTF16. + regexUniChar = uniCharBuffer; + } + + // Create the ICU regex. + if(RKL_EXPECTED((cachedRegex->icu_regex = RKL_ICU_FUNCTION_APPEND(uregex_open)(regexUniChar, (int32_t)regexStringU16Length, options, &parseError, &status)) == NULL, 0L)) { goto exitNow; } + if(RKL_EXPECTED(status <= U_ZERO_ERROR, 1L)) { cachedRegex->captureCount = (NSInteger)RKL_ICU_FUNCTION_APPEND(uregex_groupCount)(cachedRegex->icu_regex, &status); } + if(RKL_EXPECTED(status <= U_ZERO_ERROR, 1L)) { rkl_updateCachesWithCachedRegex(cachedRegex, regexString, 0, status); } + +exitNow: + if(RKL_EXPECTED(rkl_scratchBuffer[0] != NULL, 0L)) { rkl_scratchBuffer[0] = rkl_free(&rkl_scratchBuffer[0]); } + if(RKL_EXPECTED(status > U_ZERO_ERROR, 0L)) { rkl_clearCachedRegex(cachedRegex); cachedRegex = rkl_lastCachedRegex = NULL; if(error != NULL) { *error = rkl_makeNSError((RKLUserInfoOptions)RKLUserInfoNone, regexString, options, &parseError, status, NULL, NSNotFoundRange, NULL, NULL, 0L, (RKLRegexEnumerationOptions)RKLRegexEnumerationNoOptions, @"There was an error compiling the regular expression."); } } + +#ifdef _RKL_DTRACE_ENABLED + if(RKL_EXPECTED(cachedRegex == NULL, 1L)) { char regexUTF8[_RKL_DTRACE_REGEXUTF8_SIZE]; const char *err = NULL; if(status != U_ZERO_ERROR) { err = RKL_ICU_FUNCTION_APPEND(u_errorName)(status); } rkl_dtrace_getRegexUTF8((CFStringRef)regexString, regexUTF8); rkl_dtrace_compiledRegexCache(regexUTF8, options, -1, -1, status, err); } +#endif // _RKL_DTRACE_ENABLED + + return(cachedRegex); +} + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// IMPORTANT! Should only be called with rkl_cacheSpinLock already locked! +// ---------- + +#pragma mark Set a cached regular expression to a NSStrings UTF-16 text + +static NSUInteger rkl_setCachedRegexToString(RKLCachedRegex *cachedRegex, const NSRange *range, int32_t *status, id *exception RKL_UNUSED_ASSERTION_ARG) { + // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv + // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! + // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv + + RKLCDelayedAssert((cachedRegex != NULL) && (cachedRegex->setToString != NULL) && ((range != NULL) && (NSEqualRanges(*range, NSNotFoundRange) == NO)) && (status != NULL), exception, exitNow); + RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE stringUniChar = NULL; +#ifdef _RKL_DTRACE_ENABLED + unsigned int lookupResultFlags = 0U; +#endif + + NSUInteger useFixedBuffer = (cachedRegex->setToLength < (CFIndex)_RKL_FIXED_LENGTH) ? 1UL : 0UL; + RKLBuffer *buffer = NULL; + + if(cachedRegex->setToNeedsConversion == 0U) { + RKLCDelayedAssert((cachedRegex->setToUniChar != NULL) && (cachedRegex->buffer == NULL), exception, exitNow); + if(RKL_EXPECTED((stringUniChar = (RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE)CFStringGetCharactersPtr(cachedRegex->setToString)) == NULL, 0L)) { cachedRegex->setToUniChar = NULL; cachedRegex->setToRange = NSNotFoundRange; cachedRegex->setToNeedsConversion = 1U; } + else { if(RKL_EXPECTED(cachedRegex->setToUniChar != stringUniChar, 0L)) { cachedRegex->setToRange = NSNotFoundRange; cachedRegex->setToUniChar = stringUniChar; } goto setRegexText; } + } + + buffer = cachedRegex->buffer; + + RKLCDelayedAssert((buffer == NULL) ? 1 : (((buffer == &rkl_lruFixedBuffer[0]) || (buffer == &rkl_lruFixedBuffer[1]) || (buffer == &rkl_lruFixedBuffer[2]) || (buffer == &rkl_lruFixedBuffer[3])) || + ((buffer == &rkl_lruDynamicBuffer[0]) || (buffer == &rkl_lruDynamicBuffer[1]) || (buffer == &rkl_lruDynamicBuffer[2]) || (buffer == &rkl_lruDynamicBuffer[3]))), exception, exitNow); + + if((buffer != NULL) && RKL_EXPECTED(cachedRegex->setToString == buffer->string, 1L) && RKL_EXPECTED(cachedRegex->setToHash == buffer->hash, 1L) && RKL_EXPECTED(cachedRegex->setToLength == buffer->length, 1L)) { + RKLCDelayedAssert((buffer->uniChar != NULL), exception, exitNow); + rkl_dtrace_addLookupFlag(lookupResultFlags, RKLCacheHitLookupFlag | RKLConversionRequiredLookupFlag | (useFixedBuffer ? 0U : RKLDynamicBufferLookupFlag)); + if(cachedRegex->setToUniChar != buffer->uniChar) { cachedRegex->setToRange = NSNotFoundRange; cachedRegex->setToUniChar = buffer->uniChar; } + goto setRegexText; + } + + buffer = NULL; + cachedRegex->buffer = NULL; + + NSInteger cacheWay = 0L; + for(cacheWay = ((NSInteger)_RKL_LRU_CACHE_SET_WAYS - 1L); cacheWay > 0L; cacheWay--) { + if(useFixedBuffer) { buffer = &rkl_lruFixedBuffer[cacheWay]; } else { buffer = &rkl_lruDynamicBuffer[cacheWay]; } + if(RKL_EXPECTED(cachedRegex->setToString == buffer->string, 1L) && RKL_EXPECTED(cachedRegex->setToHash == buffer->hash, 1L) && RKL_EXPECTED(cachedRegex->setToLength == buffer->length, 1L)) { + RKLCDelayedAssert((buffer->uniChar != NULL), exception, exitNow); + rkl_dtrace_addLookupFlag(lookupResultFlags, RKLCacheHitLookupFlag | RKLConversionRequiredLookupFlag | (useFixedBuffer ? 0U : RKLDynamicBufferLookupFlag)); + if(cachedRegex->setToUniChar != buffer->uniChar) { cachedRegex->setToRange = NSNotFoundRange; cachedRegex->setToUniChar = buffer->uniChar; } + cachedRegex->buffer = buffer; + goto setRegexText; + } + } + + buffer = NULL; + cachedRegex->setToUniChar = NULL; + cachedRegex->setToRange = NSNotFoundRange; + cachedRegex->buffer = NULL; + + RKLCDelayedAssert((cachedRegex->setToNeedsConversion == 1U) && (cachedRegex->buffer == NULL), exception, exitNow); + if(RKL_EXPECTED(cachedRegex->setToNeedsConversion == 1U, 1L) && RKL_EXPECTED((cachedRegex->setToUniChar = (RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE)CFStringGetCharactersPtr(cachedRegex->setToString)) != NULL, 0L)) { cachedRegex->setToNeedsConversion = 0U; cachedRegex->setToRange = NSNotFoundRange; goto setRegexText; } + + rkl_dtrace_addLookupFlag(lookupResultFlags, RKLConversionRequiredLookupFlag | (useFixedBuffer ? 0U : RKLDynamicBufferLookupFlag)); + + if(useFixedBuffer) { buffer = &rkl_lruFixedBuffer [rkl_leastRecentlyUsedWayInSet(1UL, &rkl_lruFixedBufferCacheSet, 0UL)]; } + else { buffer = &rkl_lruDynamicBuffer[rkl_leastRecentlyUsedWayInSet(1UL, &rkl_lruDynamicBufferCacheSet, 0UL)]; } + + RKLCDelayedAssert((useFixedBuffer) ? ((buffer == &rkl_lruFixedBuffer[0]) || (buffer == &rkl_lruFixedBuffer[1]) || (buffer == &rkl_lruFixedBuffer[2]) || (buffer == &rkl_lruFixedBuffer[3])) : + ((buffer == &rkl_lruDynamicBuffer[0]) || (buffer == &rkl_lruDynamicBuffer[1]) || (buffer == &rkl_lruDynamicBuffer[2]) || (buffer == &rkl_lruDynamicBuffer[3])), exception, exitNow); + + rkl_clearBuffer(buffer, 0UL); + + RKLCDelayedAssert((buffer->string == NULL) && (cachedRegex->setToString != NULL), exception, exitNow); + if(RKL_EXPECTED((buffer->string = (CFStringRef)CFRetain((CFTypeRef)cachedRegex->setToString)) == NULL, 0L)) { goto exitNow; } + buffer->hash = cachedRegex->setToHash; + buffer->length = cachedRegex->setToLength; + + if(useFixedBuffer == 0UL) { + RKL_STRONG_REF void * RKL_GC_VOLATILE p = (RKL_STRONG_REF void * RKL_GC_VOLATILE)buffer->uniChar; + if(RKL_EXPECTED((buffer->uniChar = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc(&p, ((size_t)buffer->length * sizeof(UniChar)), 0UL)) == NULL, 0L)) { goto exitNow; } // Resize the buffer. + } + + RKLCDelayedAssert((buffer->string != NULL) && (buffer->uniChar != NULL), exception, exitNow); + CFStringGetCharacters(buffer->string, CFMakeRange(0L, buffer->length), (UniChar *)buffer->uniChar); // Convert to a UTF16 string. + + cachedRegex->setToUniChar = buffer->uniChar; + cachedRegex->setToRange = NSNotFoundRange; + cachedRegex->buffer = buffer; + +setRegexText: + if(buffer != NULL) { if(useFixedBuffer == 1UL) { rkl_accessCacheSetWay(1UL, &rkl_lruFixedBufferCacheSet, 0UL, (NSUInteger)(buffer - rkl_lruFixedBuffer)); } else { rkl_accessCacheSetWay(1UL, &rkl_lruDynamicBufferCacheSet, 0UL, (NSUInteger)(buffer - rkl_lruDynamicBuffer)); } } + + if(NSEqualRanges(cachedRegex->setToRange, *range) == NO) { + RKLCDelayedAssert((cachedRegex->icu_regex != NULL) && (cachedRegex->setToUniChar != NULL) && (NSMaxRange(*range) <= (NSUInteger)cachedRegex->setToLength) && (cachedRegex->setToRange.length <= INT_MAX), exception, exitNow); + cachedRegex->lastFindRange = cachedRegex->lastMatchRange = NSNotFoundRange; + cachedRegex->setToRange = *range; + RKL_ICU_FUNCTION_APPEND(uregex_setText)(cachedRegex->icu_regex, cachedRegex->setToUniChar + cachedRegex->setToRange.location, (int32_t)cachedRegex->setToRange.length, status); + rkl_dtrace_addLookupFlag(lookupResultFlags, RKLSetTextLookupFlag); + if(RKL_EXPECTED(*status > U_ZERO_ERROR, 0L)) { rkl_dtrace_addLookupFlag(lookupResultFlags, RKLErrorLookupFlag); goto exitNow; } + } + + rkl_dtrace_utf16ConversionCache(lookupResultFlags, cachedRegex->setToString, cachedRegex->setToRange.location, cachedRegex->setToRange.length, cachedRegex->setToLength); + + return(1UL); + + // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! + // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +exitNow: +#ifdef _RKL_DTRACE_ENABLED + rkl_dtrace_addLookupFlag(lookupResultFlags, RKLErrorLookupFlag); + if(cachedRegex != NULL) { rkl_dtrace_utf16ConversionCache(lookupResultFlags, cachedRegex->setToString, cachedRegex->setToRange.location, cachedRegex->setToRange.length, cachedRegex->setToLength); } +#endif // _RKL_DTRACE_ENABLED + if(cachedRegex != NULL) { cachedRegex->buffer = NULL; cachedRegex->setToRange = NSNotFoundRange; cachedRegex->lastFindRange = NSNotFoundRange; cachedRegex->lastMatchRange = NSNotFoundRange; } + return(0UL); +} + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// IMPORTANT! Should only be called with rkl_cacheSpinLock already locked! +// ---------- + +#pragma mark Get a regular expression and set it to a NSStrings UTF-16 text + +static RKLCachedRegex *rkl_getCachedRegexSetToString(NSString *regexString, RKLRegexOptions options, NSString *matchString, NSUInteger *matchLengthPtr, NSRange *matchRange, NSError **error, id *exception, int32_t *status) { + // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv + // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! + // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv + + RKLCachedRegex *cachedRegex = NULL; + RKLCDelayedAssert((regexString != NULL) && (matchString != NULL) && (exception != NULL) && (status != NULL) && (matchLengthPtr != NULL), exception, exitNow); + + if(RKL_EXPECTED((cachedRegex = rkl_getCachedRegex(regexString, options, error, exception)) == NULL, 0L)) { goto exitNow; } + RKLCDelayedAssert(((cachedRegex >= rkl_cachedRegexes) && ((cachedRegex - rkl_cachedRegexes) < (ssize_t)_RKL_REGEX_CACHE_LINES)) && (cachedRegex != NULL) && (cachedRegex->icu_regex != NULL) && (cachedRegex->regexString != NULL) && (cachedRegex->captureCount >= 0L) && (cachedRegex == rkl_lastCachedRegex), exception, exitNow); + + // Optimize the case where the string to search (matchString) is immutable and the setToString immutable copy is the same string with its reference count incremented. + NSUInteger isSetTo = ((cachedRegex->setToString == (CFStringRef)matchString)) ? 1UL : 0UL; + CFIndex matchLength = ((cachedRegex->setToIsImmutable == 1U) && (isSetTo == 1UL)) ? cachedRegex->setToLength : CFStringGetLength((CFStringRef)matchString); + + *matchLengthPtr = (NSUInteger)matchLength; + if(matchRange->length == NSUIntegerMax) { matchRange->length = (NSUInteger)matchLength; } // For convenience, allow NSUIntegerMax == string length. + + if(RKL_EXPECTED((NSUInteger)matchLength < NSMaxRange(*matchRange), 0L)) { goto exitNow; } // The match range is out of bounds for the string. performRegexOp will catch and report the problem. + + RKLCDelayedAssert((isSetTo == 1UL) ? (cachedRegex->setToString != NULL) : 1, exception, exitNow); + + if(((cachedRegex->setToIsImmutable == 1U) ? isSetTo : (NSUInteger)((isSetTo == 1UL) && (cachedRegex->setToLength == matchLength) && (cachedRegex->setToHash == CFHash((CFTypeRef)matchString)))) == 0UL) { + if(cachedRegex->setToString != NULL) { rkl_clearCachedRegexSetTo(cachedRegex); } + + cachedRegex->setToString = (CFStringRef)CFRetain((CFTypeRef)matchString); + RKLCDelayedAssert(cachedRegex->setToString != NULL, exception, exitNow); + cachedRegex->setToUniChar = CFStringGetCharactersPtr(cachedRegex->setToString); + cachedRegex->setToNeedsConversion = (cachedRegex->setToUniChar == NULL) ? 1U : 0U; + cachedRegex->setToIsImmutable = (rkl_CFStringIsMutable(cachedRegex->setToString) == YES) ? 0U : 1U; // If RKL_FAST_MUTABLE_CHECK is not defined then setToIsImmutable will always be set to '0', or in other words mutable.. + cachedRegex->setToHash = CFHash((CFTypeRef)cachedRegex->setToString); + cachedRegex->setToRange = NSNotFoundRange; + cachedRegex->setToLength = matchLength; + + } + + if(RKL_EXPECTED(rkl_setCachedRegexToString(cachedRegex, matchRange, status, exception) == 0UL, 0L)) { cachedRegex = NULL; if(*exception == NULL) { *exception = (id)RKLCAssertDictionary(@"Failed to set up UTF16 buffer."); } goto exitNow; } + +exitNow: + return(cachedRegex); + // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! + // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +} + +#pragma mark GCC cleanup __attribute__ functions that ensure the global rkl_cacheSpinLock is properly unlocked +#ifdef RKL_HAVE_CLEANUP + +// rkl_cleanup_cacheSpinLockStatus takes advantage of GCC's 'cleanup' variable attribute. When an 'auto' variable with the 'cleanup' attribute goes out of scope, +// GCC arranges to have the designated function called. In this case, we make sure that if rkl_cacheSpinLock was locked that it was also unlocked. +// If rkl_cacheSpinLock was locked, but the rkl_cacheSpinLockStatus unlocked flag was not set, we force rkl_cacheSpinLock unlocked with a call to OSSpinLockUnlock. +// This is not a panacea for preventing mutex usage errors. Old style ObjC exceptions will bypass the cleanup call, but newer C++ style ObjC exceptions should cause the cleanup function to be called during the stack unwind. + +// We do not depend on this cleanup function being called. It is used only as an extra safety net. It is probably a bug in RegexKitLite if it is ever invoked and forced to take some kind of protective action. + +volatile NSUInteger rkl_debugCacheSpinLockCount = 0UL; + +void rkl_debugCacheSpinLock (void) RKL_ATTRIBUTES(used, noinline, visibility("default")); +static void rkl_cleanup_cacheSpinLockStatus (volatile NSUInteger *rkl_cacheSpinLockStatusPtr) RKL_ATTRIBUTES(used); + +void rkl_debugCacheSpinLock(void) { + rkl_debugCacheSpinLockCount++; // This is here primarily to prevent the optimizer from optimizing away the function. +} + +static void rkl_cleanup_cacheSpinLockStatus(volatile NSUInteger *rkl_cacheSpinLockStatusPtr) { + static NSUInteger didPrintForcedUnlockWarning = 0UL, didPrintNotLockedWarning = 0UL; + NSUInteger rkl_cacheSpinLockStatus = *rkl_cacheSpinLockStatusPtr; + + if(RKL_EXPECTED((rkl_cacheSpinLockStatus & RKLUnlockedCacheSpinLock) == 0UL, 0L) && RKL_EXPECTED((rkl_cacheSpinLockStatus & RKLLockedCacheSpinLock) != 0UL, 1L)) { + if(rkl_cacheSpinLock != (OSSpinLock)0) { + if(didPrintForcedUnlockWarning == 0UL) { didPrintForcedUnlockWarning = 1UL; NSLog(@"[RegexKitLite] Unusual condition detected: Recorded that rkl_cacheSpinLock was locked, but for some reason it was not unlocked. Forcibly unlocking rkl_cacheSpinLock. Set a breakpoint at rkl_debugCacheSpinLock to debug. This warning is only printed once."); } + rkl_debugCacheSpinLock(); // Since this is an unusual condition, offer an attempt to catch it before we unlock. + OSSpinLockUnlock(&rkl_cacheSpinLock); + } else { + if(didPrintNotLockedWarning == 0UL) { didPrintNotLockedWarning = 1UL; NSLog(@"[RegexKitLite] Unusual condition detected: Recorded that rkl_cacheSpinLock was locked, but for some reason it was not unlocked, yet rkl_cacheSpinLock is currently not locked? Set a breakpoint at rkl_debugCacheSpinLock to debug. This warning is only printed once."); } + rkl_debugCacheSpinLock(); + } + } +} + +#endif // RKL_HAVE_CLEANUP + +// rkl_performDictionaryVarArgsOp is a front end to rkl_performRegexOp which converts a ', ...' varargs key/captures list and converts it in to a form that rkl_performRegexOp can use. +// All error checking of arguments is handled by rkl_performRegexOp. + +#pragma mark Front end function that handles varargs and calls rkl_performRegexOp with the marshaled results + +static id rkl_performDictionaryVarArgsOp(id self, SEL _cmd, RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, NSInteger capture, id matchString, NSRange *matchRange, NSString *replacementString, NSError **error, void *result, id firstKey, va_list varArgsList) { + id captureKeys[64]; + int captureKeyIndexes[64]; + NSUInteger captureKeysCount = 0UL; + + if(varArgsList != NULL) { + while(captureKeysCount < 62UL) { + id thisCaptureKey = (captureKeysCount == 0) ? firstKey : va_arg(varArgsList, id); + if(RKL_EXPECTED(thisCaptureKey == NULL, 0L)) { break; } + int thisCaptureKeyIndex = va_arg(varArgsList, int); + captureKeys[captureKeysCount] = thisCaptureKey; + captureKeyIndexes[captureKeysCount] = thisCaptureKeyIndex; + captureKeysCount++; + } + } + + return(rkl_performRegexOp(self, _cmd, regexOp, regexString, options, capture, matchString, matchRange, replacementString, error, result, captureKeysCount, captureKeys, captureKeyIndexes)); +} + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// ---------- + +#pragma mark Primary internal function that Objective-C methods call to perform regular expression operations + +static id rkl_performRegexOp(id self, SEL _cmd, RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, NSInteger capture, id matchString, NSRange *matchRange, NSString *replacementString, NSError **error, void *result, NSUInteger captureKeysCount, id captureKeys[captureKeysCount], const int captureKeyIndexes[captureKeysCount]) { + volatile NSUInteger RKL_CLEANUP(rkl_cleanup_cacheSpinLockStatus) rkl_cacheSpinLockStatus = 0UL; + + NSUInteger replaceMutable = 0UL; + RKLRegexOp maskedRegexOp = (regexOp & RKLMaskOp); + BOOL dictionaryOp = ((maskedRegexOp == RKLDictionaryOfCapturesOp) || (maskedRegexOp == RKLArrayOfDictionariesOfCapturesOp)) ? YES : NO; + + if((error != NULL) && (*error != NULL)) { *error = NULL; } + + if(RKL_EXPECTED(regexString == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInvalidArgumentException, @"The regular expression argument is NULL."); } + if(RKL_EXPECTED(matchString == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInternalInconsistencyException, @"The match string argument is NULL."); } + if(RKL_EXPECTED(matchRange == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInternalInconsistencyException, @"The match range argument is NULL."); } + if((maskedRegexOp == RKLReplaceOp) && RKL_EXPECTED(replacementString == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInvalidArgumentException, @"The replacement string argument is NULL."); } + if((dictionaryOp == YES) && RKL_EXPECTED(captureKeys == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInvalidArgumentException, @"The keys argument is NULL."); } + if((dictionaryOp == YES) && RKL_EXPECTED(captureKeyIndexes == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInvalidArgumentException, @"The captures argument is NULL."); } + + id resultObject = NULL, exception = NULL; + int32_t status = U_ZERO_ERROR; + RKLCachedRegex *cachedRegex = NULL; + NSUInteger stringU16Length = 0UL, tmpIdx = 0UL; + NSRange stackRanges[2048]; + RKLFindAll findAll; + + // IMPORTANT! Once we have obtained the lock, code MUST exit via 'goto exitNow;' to unlock the lock! NO EXCEPTIONS! + // ---------- + OSSpinLockLock(&rkl_cacheSpinLock); // Grab the lock and get cache entry. + rkl_cacheSpinLockStatus |= RKLLockedCacheSpinLock; + rkl_dtrace_incrementEventID(); + + if(RKL_EXPECTED((cachedRegex = rkl_getCachedRegexSetToString(regexString, options, matchString, &stringU16Length, matchRange, error, &exception, &status)) == NULL, 0L)) { stringU16Length = (NSUInteger)CFStringGetLength((CFStringRef)matchString); } + if(RKL_EXPECTED(matchRange->length == NSUIntegerMax, 0L)) { matchRange->length = stringU16Length; } // For convenience. + if(RKL_EXPECTED(stringU16Length < NSMaxRange(*matchRange), 0L) && RKL_EXPECTED(exception == NULL, 1L)) { exception = (id)RKL_EXCEPTION(NSRangeException, @"Range or index out of bounds."); goto exitNow; } + if(RKL_EXPECTED(stringU16Length >= (NSUInteger)INT_MAX, 0L) && RKL_EXPECTED(exception == NULL, 1L)) { exception = (id)RKL_EXCEPTION(NSRangeException, @"String length exceeds INT_MAX."); goto exitNow; } + if(((maskedRegexOp == RKLRangeOp) || (maskedRegexOp == RKLArrayOfStringsOp)) && RKL_EXPECTED(cachedRegex != NULL, 1L) && (RKL_EXPECTED(capture < 0L, 0L) || RKL_EXPECTED(capture > cachedRegex->captureCount, 0L)) && RKL_EXPECTED(exception == NULL, 1L)) { exception = (id)RKL_EXCEPTION(NSInvalidArgumentException, @"The capture argument is not valid."); goto exitNow; } + + if((dictionaryOp == YES) && RKL_EXPECTED(cachedRegex != NULL, 1L) && RKL_EXPECTED(exception == NULL, 1L)) { + for(tmpIdx = 0UL; tmpIdx < captureKeysCount; tmpIdx++) { + if(RKL_EXPECTED(captureKeys[tmpIdx] == NULL, 0L)) { exception = (id)RKL_EXCEPTION(NSInvalidArgumentException, @"The capture key (key %lu of %lu) is NULL.", (unsigned long)(tmpIdx + 1UL), (unsigned long)captureKeysCount); break; } + if((RKL_EXPECTED(captureKeyIndexes[tmpIdx] < 0, 0L) || RKL_EXPECTED(captureKeyIndexes[tmpIdx] > cachedRegex->captureCount, 0L))) { exception = (id)RKL_EXCEPTION(NSInvalidArgumentException, @"The capture argument %d (capture %lu of %lu) for key '%@' is not valid.", captureKeyIndexes[tmpIdx], (unsigned long)(tmpIdx + 1UL), (unsigned long)captureKeysCount, captureKeys[tmpIdx]); break; } + } + } + + if(RKL_EXPECTED(cachedRegex == NULL, 0L) || RKL_EXPECTED(status > U_ZERO_ERROR, 0L) || RKL_EXPECTED(exception != NULL, 0L)) { goto exitNow; } + + RKLCDelayedAssert(((cachedRegex >= rkl_cachedRegexes) && ((cachedRegex - rkl_cachedRegexes) < (ssize_t)_RKL_REGEX_CACHE_LINES)) && (cachedRegex != NULL) && (cachedRegex->icu_regex != NULL) && (cachedRegex->regexString != NULL) && (cachedRegex->captureCount >= 0L) && (cachedRegex->setToString != NULL) && (cachedRegex->setToLength >= 0L) && (cachedRegex->setToUniChar != NULL) && ((CFIndex)NSMaxRange(cachedRegex->setToRange) <= cachedRegex->setToLength), &exception, exitNow); + RKLCDelayedAssert((cachedRegex->setToNeedsConversion == 0U) ? ((cachedRegex->setToNeedsConversion == 0U) && (cachedRegex->setToUniChar == CFStringGetCharactersPtr(cachedRegex->setToString))) : ((cachedRegex->buffer != NULL) && (cachedRegex->setToHash == cachedRegex->buffer->hash) && (cachedRegex->setToLength == cachedRegex->buffer->length) && (cachedRegex->setToUniChar == cachedRegex->buffer->uniChar)), &exception, exitNow); + + switch(maskedRegexOp) { + case RKLRangeOp: + if((RKL_EXPECTED(rkl_search(cachedRegex, matchRange, 0UL, &exception, &status) == NO, 0L)) || (RKL_EXPECTED(status > U_ZERO_ERROR, 0L))) { *(NSRange *)result = NSNotFoundRange; goto exitNow; } + if(RKL_EXPECTED(capture == 0L, 1L)) { *(NSRange *)result = cachedRegex->lastMatchRange; } else { if(RKL_EXPECTED(rkl_getRangeForCapture(cachedRegex, &status, (int32_t)capture, (NSRange *)result) > U_ZERO_ERROR, 0L)) { goto exitNow; } } + break; + + case RKLSplitOp: // Fall-thru... + case RKLArrayOfStringsOp: // Fall-thru... + case RKLCapturesArrayOp: // Fall-thru... + case RKLArrayOfCapturesOp: // Fall-thru... + case RKLDictionaryOfCapturesOp: // Fall-thru... + case RKLArrayOfDictionariesOfCapturesOp: + findAll = rkl_makeFindAll(stackRanges, *matchRange, 2048L, (2048UL * sizeof(NSRange)), 0UL, &rkl_scratchBuffer[0], &rkl_scratchBuffer[1], &rkl_scratchBuffer[2], &rkl_scratchBuffer[3], &rkl_scratchBuffer[4], 0L, capture, (((maskedRegexOp == RKLCapturesArrayOp) || (maskedRegexOp == RKLDictionaryOfCapturesOp)) ? 1L : NSIntegerMax)); + + if(RKL_EXPECTED(rkl_findRanges(cachedRegex, regexOp, &findAll, &exception, &status) == NO, 1L)) { + if(RKL_EXPECTED(findAll.found == 0L, 0L)) { resultObject = (maskedRegexOp == RKLDictionaryOfCapturesOp) ? [NSDictionary dictionary] : [NSArray array]; } + else { + if(dictionaryOp == YES) { resultObject = rkl_makeDictionary (cachedRegex, regexOp, &findAll, captureKeysCount, captureKeys, captureKeyIndexes, &exception); } + else { resultObject = rkl_makeArray (cachedRegex, regexOp, &findAll, &exception); } + } + } + + for(tmpIdx = 0UL; tmpIdx < _RKL_SCRATCH_BUFFERS; tmpIdx++) { if(RKL_EXPECTED(rkl_scratchBuffer[tmpIdx] != NULL, 0L)) { rkl_scratchBuffer[tmpIdx] = rkl_free(&rkl_scratchBuffer[tmpIdx]); } } + + break; + + case RKLReplaceOp: resultObject = rkl_replaceString(cachedRegex, matchString, stringU16Length, replacementString, (NSUInteger)CFStringGetLength((CFStringRef)replacementString), (NSInteger *)result, (replaceMutable = (((regexOp & RKLReplaceMutable) != 0) ? 1UL : 0UL)), &exception, &status); break; + + default: exception = RKLCAssertDictionary(@"Unknown regexOp code."); break; + } + +exitNow: + OSSpinLockUnlock(&rkl_cacheSpinLock); + rkl_cacheSpinLockStatus |= RKLUnlockedCacheSpinLock; // Warning about rkl_cacheSpinLockStatus never being read can be safely ignored. + + if(RKL_EXPECTED(status > U_ZERO_ERROR, 0L) && RKL_EXPECTED(exception == NULL, 0L)) { exception = rkl_NSExceptionForRegex(regexString, options, NULL, status); } // If we had a problem, prepare an exception to be thrown. + if(RKL_EXPECTED(exception != NULL, 0L)) { rkl_handleDelayedAssert(self, _cmd, exception); } // If there is an exception, throw it at this point. + // If we're working on a mutable string and there were successful matches/replacements, then we still have work to do. + // This is done outside the cache lock and with the objc replaceCharactersInRange:withString: method because Core Foundation + // does not assert that the string we are attempting to update is actually a mutable string, whereas Foundation ensures + // the object receiving the message is a mutable string and throws an exception if we're attempting to modify an immutable string. + if(RKL_EXPECTED(replaceMutable == 1UL, 0L) && RKL_EXPECTED(*((NSInteger *)result) > 0L, 1L) && RKL_EXPECTED(status == U_ZERO_ERROR, 1L) && RKL_EXPECTED(resultObject != NULL, 1L)) { [matchString replaceCharactersInRange:*matchRange withString:resultObject]; } + // If status < U_ZERO_ERROR, consider it an error, even though status < U_ZERO_ERROR is a 'warning' in ICU nomenclature. + // status > U_ZERO_ERROR are an exception and handled above. + // http://sourceforge.net/tracker/?func=detail&atid=990188&aid=2890810&group_id=204582 + if(RKL_EXPECTED(status < U_ZERO_ERROR, 0L) && RKL_EXPECTED(resultObject == NULL, 0L) && (error != NULL)) { + NSString *replacedString = NULL; + NSInteger replacedCount = 0L; + RKLUserInfoOptions userInfoOptions = RKLUserInfoNone; + if((maskedRegexOp == RKLReplaceOp) && (result != NULL)) { userInfoOptions |= RKLUserInfoReplacedCount; replacedString = resultObject; replacedCount = *((NSInteger *)result); } + if(matchRange != NULL) { userInfoOptions |= RKLUserInfoSubjectRange; } + *error = rkl_makeNSError(userInfoOptions, regexString, options, NULL, status, matchString, (matchRange != NULL) ? *matchRange : NSNotFoundRange, replacementString, replacedString, replacedCount, (RKLRegexEnumerationOptions)RKLRegexEnumerationNoOptions, @"The ICU library returned an unexpected error."); + } + return(resultObject); +} + +static void rkl_handleDelayedAssert(id self, SEL _cmd, id exception) { + if(RKL_EXPECTED(exception != NULL, 1L)) { + if([exception isKindOfClass:[NSException class]]) { [[NSException exceptionWithName:[exception name] reason:rkl_stringFromClassAndMethod(self, _cmd, [exception reason]) userInfo:[exception userInfo]] raise]; } + else { + id functionString = [exception objectForKey:@"function"], fileString = [exception objectForKey:@"file"], descriptionString = [exception objectForKey:@"description"], lineNumber = [exception objectForKey:@"line"]; + RKLCHardAbortAssert((functionString != NULL) && (fileString != NULL) && (descriptionString != NULL) && (lineNumber != NULL)); + [[NSAssertionHandler currentHandler] handleFailureInFunction:functionString file:fileString lineNumber:(NSInteger)[lineNumber longValue] description:descriptionString]; + } + } +} + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// IMPORTANT! Should only be called from rkl_performRegexOp() or rkl_findRanges(). +// ---------- + +#pragma mark Primary means of performing a search with a regular expression + +static NSUInteger rkl_search(RKLCachedRegex *cachedRegex, NSRange *searchRange, NSUInteger updateSearchRange, id *exception RKL_UNUSED_ASSERTION_ARG, int32_t *status) { + NSUInteger foundMatch = 0UL; + + if((NSEqualRanges(*searchRange, cachedRegex->lastFindRange) == YES) && ((cachedRegex->lastMatchRange.length > 0UL) || (cachedRegex->lastMatchRange.location == (NSUInteger)NSNotFound))) { foundMatch = ((cachedRegex->lastMatchRange.location == (NSUInteger)NSNotFound) ? 0UL : 1UL);} + else { // Only perform an expensive 'find' operation iff the current find range is different than the last find range. + NSUInteger findLocation = (searchRange->location - cachedRegex->setToRange.location); + RKLCDelayedAssert(((searchRange->location >= cachedRegex->setToRange.location)) && (NSRangeInsideRange(*searchRange, cachedRegex->setToRange) == YES) && (findLocation < INT_MAX) && (findLocation <= cachedRegex->setToRange.length), exception, exitNow); + + RKL_PREFETCH_UNICHAR(cachedRegex->setToUniChar, searchRange->location); // Spool up the CPU caches. + + // Using uregex_findNext can be a slight performance win. + NSUInteger useFindNext = (RKL_EXPECTED(searchRange->location == (NSMaxRange(cachedRegex->lastMatchRange) + ((RKL_EXPECTED(cachedRegex->lastMatchRange.length == 0UL, 0L) && RKL_EXPECTED(cachedRegex->lastMatchRange.location < NSMaxRange(cachedRegex->setToRange), 0L)) ? 1UL : 0UL)), 1L) ? 1UL : 0UL); + + cachedRegex->lastFindRange = *searchRange; + if(RKL_EXPECTED(useFindNext == 0UL, 0L)) { if(RKL_EXPECTED((RKL_ICU_FUNCTION_APPEND(uregex_find) (cachedRegex->icu_regex, (int32_t)findLocation, status) == NO), 0L) || RKL_EXPECTED(*status > U_ZERO_ERROR, 0L)) { goto finishedFind; } } + else { if(RKL_EXPECTED((RKL_ICU_FUNCTION_APPEND(uregex_findNext)(cachedRegex->icu_regex, status) == NO), 0L) || RKL_EXPECTED(*status > U_ZERO_ERROR, 0L)) { goto finishedFind; } } + foundMatch = 1UL; + + if(RKL_EXPECTED(rkl_getRangeForCapture(cachedRegex, status, 0, &cachedRegex->lastMatchRange) > U_ZERO_ERROR, 0L)) { goto finishedFind; } + RKLCDelayedAssert(NSRangeInsideRange(cachedRegex->lastMatchRange, *searchRange) == YES, exception, exitNow); + } + +finishedFind: + if(RKL_EXPECTED(*status > U_ZERO_ERROR, 0L)) { foundMatch = 0UL; cachedRegex->lastFindRange = NSNotFoundRange; } + + if(RKL_EXPECTED(foundMatch == 0UL, 0L)) { cachedRegex->lastFindRange = NSNotFoundRange; cachedRegex->lastMatchRange = NSNotFoundRange; if(RKL_EXPECTED(updateSearchRange == 1UL, 1L)) { *searchRange = NSMakeRange(NSMaxRange(*searchRange), 0UL); } } + else { + RKLCDelayedAssert(NSRangeInsideRange(cachedRegex->lastMatchRange, *searchRange) == YES, exception, exitNow); + if(RKL_EXPECTED(updateSearchRange == 1UL, 1L)) { + NSUInteger nextLocation = (NSMaxRange(cachedRegex->lastMatchRange) + ((RKL_EXPECTED(cachedRegex->lastMatchRange.length == 0UL, 0L) && RKL_EXPECTED(cachedRegex->lastMatchRange.location < NSMaxRange(cachedRegex->setToRange), 1L)) ? 1UL : 0UL)), locationDiff = nextLocation - searchRange->location; + RKLCDelayedAssert((((locationDiff > 0UL) || ((locationDiff == 0UL) && (cachedRegex->lastMatchRange.location == NSMaxRange(cachedRegex->setToRange)))) && (locationDiff <= searchRange->length)), exception, exitNow); + searchRange->location = nextLocation; + searchRange->length -= locationDiff; + } + } + +#ifndef NS_BLOCK_ASSERTIONS +exitNow: +#endif + return(foundMatch); +} + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// IMPORTANT! Should only be called from rkl_performRegexOp() or rkl_performEnumerationUsingBlock(). +// ---------- + +#pragma mark Used to perform multiple searches at once and return the NSRange results in bulk + +static BOOL rkl_findRanges(RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, id *exception, int32_t *status) { + BOOL returnWithError = YES; + RKLCDelayedAssert((((cachedRegex != NULL) && (cachedRegex->icu_regex != NULL) && (cachedRegex->setToUniChar != NULL) && (cachedRegex->captureCount >= 0L) && (cachedRegex->setToRange.location != (NSUInteger)NSNotFound)) && (status != NULL) && ((findAll != NULL) && (findAll->found == 0L) && (findAll->addedSplitRanges == 0L) && ((findAll->capacity >= 0L) && (((findAll->capacity > 0L) || (findAll->size > 0UL)) ? ((findAll->ranges != NULL) && (findAll->capacity > 0L) && (findAll->size > 0UL)) : 1)) && ((findAll->capture >= 0L) && (findAll->capture <= cachedRegex->captureCount)))), exception, exitNow); + + NSInteger captureCount = cachedRegex->captureCount, findAllRangeIndexOfLastNonZeroLength = 0L; + NSUInteger lastLocation = findAll->findInRange.location; + RKLRegexOp maskedRegexOp = (regexOp & RKLMaskOp); + NSRange searchRange = findAll->findInRange; + + for(findAll->found = 0L; (findAll->found < findAll->findUpTo) && ((findAll->found < findAll->capacity) || (findAll->found == 0L)); findAll->found++) { + NSInteger loopCapture, shouldBreak = 0L; + + if(RKL_EXPECTED(findAll->found >= ((findAll->capacity - ((captureCount + 2L) * 4L)) - 4L), 0L)) { if(RKL_EXPECTED(rkl_growFindRanges(cachedRegex, lastLocation, findAll, exception) == 0UL, 0L)) { goto exitNow; } } + + RKLCDelayedAssert((searchRange.location != (NSUInteger)NSNotFound) && (NSRangeInsideRange(searchRange, cachedRegex->setToRange) == YES) && (NSRangeInsideRange(findAll->findInRange, cachedRegex->setToRange) == YES), exception, exitNow); + + // This fixes a 'bug' that is also present in ICU's uregex_split(). 'Bug', in this case, means that the results of a split operation can differ from those that perl's split() creates for the same input. + // "I|at|ice I eat rice" split using the regex "\b\s*" demonstrates the problem. ICU bug http://bugs.icu-project.org/trac/ticket/6826 + // ICU : "", "I", "|", "at", "|", "ice", "", "I", "", "eat", "", "rice" <- Results that RegexKitLite used to produce. + // PERL: "I", "|", "at", "|", "ice", "I", "eat", "rice" <- Results that RegexKitLite now produces. + do { if((rkl_search(cachedRegex, &searchRange, 1UL, exception, status) == NO) || (RKL_EXPECTED(*status > U_ZERO_ERROR, 0L))) { shouldBreak = 1L; } findAll->remainingRange = searchRange; } + while(RKL_EXPECTED((cachedRegex->lastMatchRange.location - lastLocation) == 0UL, 0L) && RKL_EXPECTED(cachedRegex->lastMatchRange.length == 0UL, 0L) && (maskedRegexOp == RKLSplitOp) && RKL_EXPECTED(shouldBreak == 0L, 1L)); + if(RKL_EXPECTED(shouldBreak == 1L, 0L)) { break; } + + RKLCDelayedAssert((searchRange.location != (NSUInteger)NSNotFound) && (NSRangeInsideRange(searchRange, cachedRegex->setToRange) == YES) && (NSRangeInsideRange(findAll->findInRange, cachedRegex->setToRange) == YES) && (NSRangeInsideRange(searchRange, findAll->findInRange) == YES), exception, exitNow); + RKLCDelayedAssert((NSRangeInsideRange(cachedRegex->lastFindRange, cachedRegex->setToRange) == YES) && (NSRangeInsideRange(cachedRegex->lastMatchRange, cachedRegex->setToRange) == YES) && (NSRangeInsideRange(cachedRegex->lastMatchRange, findAll->findInRange) == YES), exception, exitNow); + RKLCDelayedAssert((findAll->ranges != NULL) && (findAll->found >= 0L) && (findAll->capacity >= 0L) && ((findAll->found + (captureCount + 3L) + 1L) < (findAll->capacity - 2L)), exception, exitNow); + + NSInteger findAllRangesIndexForCapture0 = findAll->found; + switch(maskedRegexOp) { + case RKLArrayOfStringsOp: + if(findAll->capture == 0L) { findAll->ranges[findAll->found] = cachedRegex->lastMatchRange; } else { if(RKL_EXPECTED(rkl_getRangeForCapture(cachedRegex, status, (int32_t)findAll->capture, &findAll->ranges[findAll->found]) > U_ZERO_ERROR, 0L)) { goto exitNow; } } + break; + + case RKLSplitOp: // Fall-thru... + case RKLCapturesArrayOp: // Fall-thru... + case RKLDictionaryOfCapturesOp: // Fall-thru... + case RKLArrayOfDictionariesOfCapturesOp: // Fall-thru... + case RKLArrayOfCapturesOp: + findAll->ranges[findAll->found] = ((maskedRegexOp == RKLSplitOp) ? NSMakeRange(lastLocation, cachedRegex->lastMatchRange.location - lastLocation) : cachedRegex->lastMatchRange); + + for(loopCapture = 1L; loopCapture <= captureCount; loopCapture++) { + RKLCDelayedAssert((findAll->found >= 0L) && (findAll->found < (findAll->capacity - 2L)) && (loopCapture < INT_MAX), exception, exitNow); + if(RKL_EXPECTED(rkl_getRangeForCapture(cachedRegex, status, (int32_t)loopCapture, &findAll->ranges[++findAll->found]) > U_ZERO_ERROR, 0L)) { goto exitNow; } + } + break; + + default: if(*exception == NULL) { *exception = RKLCAssertDictionary(@"Unknown regexOp."); } goto exitNow; break; + } + + if(findAll->ranges[findAllRangesIndexForCapture0].length > 0UL) { findAllRangeIndexOfLastNonZeroLength = findAll->found + 1UL; } + lastLocation = NSMaxRange(cachedRegex->lastMatchRange); + } + + if(RKL_EXPECTED(*status > U_ZERO_ERROR, 0L)) { goto exitNow; } + + RKLCDelayedAssert((findAll->ranges != NULL) && (findAll->found >= 0L) && (findAll->found < (findAll->capacity - 2L)), exception, exitNow); + if(maskedRegexOp == RKLSplitOp) { + if(lastLocation != NSMaxRange(findAll->findInRange)) { findAll->addedSplitRanges++; findAll->ranges[findAll->found++] = NSMakeRange(lastLocation, NSMaxRange(findAll->findInRange) - lastLocation); findAllRangeIndexOfLastNonZeroLength = findAll->found; } + findAll->found = findAllRangeIndexOfLastNonZeroLength; + } + + RKLCDelayedAssert((findAll->ranges != NULL) && (findAll->found >= 0L) && (findAll->found < (findAll->capacity - 2L)), exception, exitNow); + returnWithError = NO; + +exitNow: + return(returnWithError); +} + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// IMPORTANT! Should only be called from rkl_findRanges(). +// ---------- + +static NSUInteger rkl_growFindRanges(RKLCachedRegex *cachedRegex, NSUInteger lastLocation, RKLFindAll *findAll, id *exception RKL_UNUSED_ASSERTION_ARG) { + NSUInteger didGrowRanges = 0UL; + RKLCDelayedAssert((((cachedRegex != NULL) && (cachedRegex->captureCount >= 0L)) && ((findAll != NULL) && (findAll->capacity >= 0L) && (findAll->rangesScratchBuffer != NULL) && (findAll->found >= 0L) && (((findAll->capacity > 0L) || (findAll->size > 0UL) || (findAll->ranges != NULL)) ? ((findAll->capacity > 0L) && (findAll->size > 0UL) && (findAll->ranges != NULL) && (((size_t)findAll->capacity * sizeof(NSRange)) == findAll->size)) : 1))), exception, exitNow); + + // Attempt to guesstimate the required capacity based on: the total length needed to search / (length we've searched so far / ranges found so far). + NSInteger newCapacity = (findAll->capacity + (findAll->capacity / 2L)), estimate = (NSInteger)((float)cachedRegex->setToLength / (((float)lastLocation + 1.0f) / ((float)findAll->found + 1.0f))); + newCapacity = (((newCapacity + ((estimate > newCapacity) ? estimate : newCapacity)) / 2L) + ((cachedRegex->captureCount + 2L) * 4L) + 4L); + + NSUInteger needToCopy = ((*findAll->rangesScratchBuffer != findAll->ranges) && (findAll->ranges != NULL)) ? 1UL : 0UL; // If findAll->ranges is set to a stack allocation then we need to manually copy the data from the stack to the new heap allocation. + size_t newSize = ((size_t)newCapacity * sizeof(NSRange)); + RKL_STRONG_REF NSRange * RKL_GC_VOLATILE newRanges = NULL; + + if(RKL_EXPECTED((newRanges = (RKL_STRONG_REF NSRange * RKL_GC_VOLATILE)rkl_realloc((RKL_STRONG_REF void ** RKL_GC_VOLATILE)findAll->rangesScratchBuffer, newSize, 0UL)) == NULL, 0L)) { findAll->capacity = 0L; findAll->size = 0UL; findAll->ranges = NULL; *findAll->rangesScratchBuffer = rkl_free((RKL_STRONG_REF void ** RKL_GC_VOLATILE)findAll->rangesScratchBuffer); goto exitNow; } else { didGrowRanges = 1UL; } + if(needToCopy == 1UL) { memcpy(newRanges, findAll->ranges, findAll->size); } // If necessary, copy the existing data to the new heap allocation. + + findAll->capacity = newCapacity; + findAll->size = newSize; + findAll->ranges = newRanges; + +exitNow: + return(didGrowRanges); +} + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// IMPORTANT! Should only be called from rkl_performRegexOp(). +// ---------- + +#pragma mark Convert bulk results from rkl_findRanges in to various NSArray types + +static NSArray *rkl_makeArray(RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, id *exception RKL_UNUSED_ASSERTION_ARG) { + NSUInteger createdStringsCount = 0UL, createdArraysCount = 0UL, transferredStringsCount = 0UL; + id * RKL_GC_VOLATILE matchedStrings = NULL, * RKL_GC_VOLATILE subcaptureArrays = NULL, emptyString = @""; + NSArray * RKL_GC_VOLATILE resultArray = NULL; + + RKLCDelayedAssert((cachedRegex != NULL) && ((findAll != NULL) && (findAll->found >= 0L) && (findAll->stringsScratchBuffer != NULL) && (findAll->arraysScratchBuffer != NULL)), exception, exitNow); + + size_t matchedStringsSize = ((size_t)findAll->found * sizeof(id)); + CFStringRef setToString = cachedRegex->setToString; + + if((findAll->stackUsed + matchedStringsSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((matchedStrings = (id * RKL_GC_VOLATILE)alloca(matchedStringsSize)) == NULL, 0L)) { goto exitNow; } findAll->stackUsed += matchedStringsSize; } + else { if(RKL_EXPECTED((matchedStrings = (id * RKL_GC_VOLATILE)rkl_realloc(findAll->stringsScratchBuffer, matchedStringsSize, (NSUInteger)RKLScannedOption)) == NULL, 0L)) { goto exitNow; } } + + { // This sub-block (and its local variables) is here for the benefit of the optimizer. + NSUInteger found = (NSUInteger)findAll->found; + const NSRange *rangePtr = findAll->ranges; + id *matchedStringsPtr = matchedStrings; + + for(createdStringsCount = 0UL; createdStringsCount < found; createdStringsCount++) { + NSRange range = *rangePtr++; + if(RKL_EXPECTED(((*matchedStringsPtr++ = RKL_EXPECTED(range.length == 0UL, 0L) ? emptyString : rkl_CreateStringWithSubstring((id)setToString, range)) == NULL), 0L)) { goto exitNow; } + } + } + + NSUInteger arrayCount = createdStringsCount; + id * RKL_GC_VOLATILE arrayObjects = matchedStrings; + + if((regexOp & RKLSubcapturesArray) != 0UL) { + RKLCDelayedAssert(((createdStringsCount % ((NSUInteger)cachedRegex->captureCount + 1UL)) == 0UL) && (createdArraysCount == 0UL), exception, exitNow); + + NSUInteger captureCount = ((NSUInteger)cachedRegex->captureCount + 1UL); + NSUInteger subcaptureArraysCount = (createdStringsCount / captureCount); + size_t subcaptureArraysSize = ((size_t)subcaptureArraysCount * sizeof(id)); + + if((findAll->stackUsed + subcaptureArraysSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((subcaptureArrays = (id * RKL_GC_VOLATILE)alloca(subcaptureArraysSize)) == NULL, 0L)) { goto exitNow; } findAll->stackUsed += subcaptureArraysSize; } + else { if(RKL_EXPECTED((subcaptureArrays = (id * RKL_GC_VOLATILE)rkl_realloc(findAll->arraysScratchBuffer, subcaptureArraysSize, (NSUInteger)RKLScannedOption)) == NULL, 0L)) { goto exitNow; } } + + { // This sub-block (and its local variables) is here for the benefit of the optimizer. + id *subcaptureArraysPtr = subcaptureArrays; + id *matchedStringsPtr = matchedStrings; + + for(createdArraysCount = 0UL; createdArraysCount < subcaptureArraysCount; createdArraysCount++) { + if(RKL_EXPECTED((*subcaptureArraysPtr++ = rkl_CreateArrayWithObjects((void **)matchedStringsPtr, captureCount)) == NULL, 0L)) { goto exitNow; } + matchedStringsPtr += captureCount; + transferredStringsCount += captureCount; + } + } + + RKLCDelayedAssert((transferredStringsCount == createdStringsCount), exception, exitNow); + arrayCount = createdArraysCount; + arrayObjects = subcaptureArrays; + } + + RKLCDelayedAssert((arrayObjects != NULL), exception, exitNow); + resultArray = rkl_CreateAutoreleasedArray((void **)arrayObjects, (NSUInteger)arrayCount); + +exitNow: + if(RKL_EXPECTED(resultArray == NULL, 0L) && (rkl_collectingEnabled() == NO)) { // If we did not create an array then we need to make sure that we release any objects we created. + NSUInteger x; + if(matchedStrings != NULL) { for(x = transferredStringsCount; x < createdStringsCount; x++) { if((matchedStrings[x] != NULL) && (matchedStrings[x] != emptyString)) { matchedStrings[x] = rkl_ReleaseObject(matchedStrings[x]); } } } + if(subcaptureArrays != NULL) { for(x = 0UL; x < createdArraysCount; x++) { if(subcaptureArrays[x] != NULL) { subcaptureArrays[x] = rkl_ReleaseObject(subcaptureArrays[x]); } } } + } + + return(resultArray); +} + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// IMPORTANT! Should only be called from rkl_performRegexOp(). +// ---------- + +#pragma mark Convert bulk results from rkl_findRanges in to various NSDictionary types + +static id rkl_makeDictionary(RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, NSUInteger captureKeysCount, id captureKeys[captureKeysCount], const int captureKeyIndexes[captureKeysCount], id *exception RKL_UNUSED_ASSERTION_ARG) { + NSUInteger matchedStringIndex = 0UL, createdStringsCount = 0UL, createdDictionariesCount = 0UL, matchedDictionariesCount = (findAll->found / (cachedRegex->captureCount + 1UL)), transferredDictionariesCount = 0UL; + id * RKL_GC_VOLATILE matchedStrings = NULL, * RKL_GC_VOLATILE matchedKeys = NULL, emptyString = @""; + id RKL_GC_VOLATILE returnObject = NULL; + NSDictionary ** RKL_GC_VOLATILE matchedDictionaries = NULL; + + RKLCDelayedAssert((cachedRegex != NULL) && ((findAll != NULL) && (findAll->found >= 0L) && (findAll->stringsScratchBuffer != NULL) && (findAll->dictionariesScratchBuffer != NULL) && (findAll->keysScratchBuffer != NULL) && (captureKeyIndexes != NULL)), exception, exitNow); + + CFStringRef setToString = cachedRegex->setToString; + + size_t matchedStringsSize = ((size_t)captureKeysCount * sizeof(void *)); + if((findAll->stackUsed + matchedStringsSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((matchedStrings = (id * RKL_GC_VOLATILE)alloca(matchedStringsSize)) == NULL, 0L)) { goto exitNow; } findAll->stackUsed += matchedStringsSize; } + else { if(RKL_EXPECTED((matchedStrings = (id * RKL_GC_VOLATILE)rkl_realloc(findAll->stringsScratchBuffer, matchedStringsSize, (NSUInteger)RKLScannedOption)) == NULL, 0L)) { goto exitNow; } } + + size_t matchedKeysSize = ((size_t)captureKeysCount * sizeof(void *)); + if((findAll->stackUsed + matchedKeysSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((matchedKeys = (id * RKL_GC_VOLATILE)alloca(matchedKeysSize)) == NULL, 0L)) { goto exitNow; } findAll->stackUsed += matchedKeysSize; } + else { if(RKL_EXPECTED((matchedKeys = (id * RKL_GC_VOLATILE)rkl_realloc(findAll->keysScratchBuffer, matchedKeysSize, (NSUInteger)RKLScannedOption)) == NULL, 0L)) { goto exitNow; } } + + size_t matchedDictionariesSize = ((size_t)matchedDictionariesCount * sizeof(NSDictionary *)); + if((findAll->stackUsed + matchedDictionariesSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((matchedDictionaries = (NSDictionary ** RKL_GC_VOLATILE)alloca(matchedDictionariesSize)) == NULL, 0L)) { goto exitNow; } findAll->stackUsed += matchedDictionariesSize; } + else { if(RKL_EXPECTED((matchedDictionaries = (NSDictionary ** RKL_GC_VOLATILE)rkl_realloc(findAll->dictionariesScratchBuffer, matchedDictionariesSize, (NSUInteger)RKLScannedOption)) == NULL, 0L)) { goto exitNow; } } + + { // This sub-block (and its local variables) is here for the benefit of the optimizer. + NSUInteger captureCount = cachedRegex->captureCount; + NSDictionary **matchedDictionariesPtr = matchedDictionaries; + + for(createdDictionariesCount = 0UL; createdDictionariesCount < matchedDictionariesCount; createdDictionariesCount++) { + RKLCDelayedAssert(((createdDictionariesCount * captureCount) < (NSUInteger)findAll->found), exception, exitNow); + RKL_STRONG_REF const NSRange * RKL_GC_VOLATILE rangePtr = &findAll->ranges[(createdDictionariesCount * (captureCount + 1UL))]; + for(matchedStringIndex = 0UL; matchedStringIndex < captureKeysCount; matchedStringIndex++) { + NSRange range = rangePtr[captureKeyIndexes[matchedStringIndex]]; + if(RKL_EXPECTED(range.location != NSNotFound, 0L)) { + if(RKL_EXPECTED(((matchedStrings[createdStringsCount] = RKL_EXPECTED(range.length == 0UL, 0L) ? emptyString : rkl_CreateStringWithSubstring((id)setToString, range)) == NULL), 0L)) { goto exitNow; } + matchedKeys[createdStringsCount] = captureKeys[createdStringsCount]; + createdStringsCount++; + } + } + RKLCDelayedAssert((matchedStringIndex <= captureCount), exception, exitNow); + if(RKL_EXPECTED(((*matchedDictionariesPtr++ = (NSDictionary * RKL_GC_VOLATILE)CFDictionaryCreate(NULL, (const void **)matchedKeys, (const void **)matchedStrings, (CFIndex)createdStringsCount, &rkl_transferOwnershipDictionaryKeyCallBacks, &rkl_transferOwnershipDictionaryValueCallBacks)) == NULL), 0L)) { goto exitNow; } + createdStringsCount = 0UL; + } + } + + if(createdDictionariesCount > 0UL) { + if((regexOp & RKLMaskOp) == RKLArrayOfDictionariesOfCapturesOp) { + RKLCDelayedAssert((matchedDictionaries != NULL) && (createdDictionariesCount > 0UL), exception, exitNow); + if((returnObject = rkl_CreateAutoreleasedArray((void **)matchedDictionaries, createdDictionariesCount)) == NULL) { goto exitNow; } + transferredDictionariesCount = createdDictionariesCount; + } else { + RKLCDelayedAssert((matchedDictionaries != NULL) && (createdDictionariesCount == 1UL), exception, exitNow); + if((returnObject = rkl_CFAutorelease(matchedDictionaries[0])) == NULL) { goto exitNow; } + transferredDictionariesCount = 1UL; + } + } + +exitNow: + RKLCDelayedAssert((createdDictionariesCount <= transferredDictionariesCount) && ((transferredDictionariesCount > 0UL) ? (createdStringsCount == 0UL) : 1), exception, exitNow2); +#ifndef NS_BLOCK_ASSERTIONS +exitNow2: +#endif + + if(rkl_collectingEnabled() == NO) { // Release any objects, if necessary. + NSUInteger x; + if(matchedStrings != NULL) { for(x = 0UL; x < createdStringsCount; x++) { if((matchedStrings[x] != NULL) && (matchedStrings[x] != emptyString)) { matchedStrings[x] = rkl_ReleaseObject(matchedStrings[x]); } } } + if(matchedDictionaries != NULL) { for(x = transferredDictionariesCount; x < createdDictionariesCount; x++) { if((matchedDictionaries[x] != NULL)) { matchedDictionaries[x] = rkl_ReleaseObject(matchedDictionaries[x]); } } } + } + + return(returnObject); +} + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// IMPORTANT! Should only be called from rkl_performRegexOp(). +// ---------- + +#pragma mark Perform "search and replace" operations on strings using ICUs uregex_*replace* functions + +static NSString *rkl_replaceString(RKLCachedRegex *cachedRegex, id searchString, NSUInteger searchU16Length, NSString *replacementString, NSUInteger replacementU16Length, NSInteger *replacedCountPtr, NSUInteger replaceMutable, id *exception, int32_t *status) { + RKL_STRONG_REF UniChar * RKL_GC_VOLATILE tempUniCharBuffer = NULL; + RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE replacementUniChar = NULL; + uint64_t searchU16Length64 = (uint64_t)searchU16Length, replacementU16Length64 = (uint64_t)replacementU16Length; + int32_t resultU16Length = 0, tempUniCharBufferU16Capacity = 0, needU16Capacity = 0; + id RKL_GC_VOLATILE resultObject = NULL; + NSInteger replacedCount = -1L; + + if((RKL_EXPECTED(replacementU16Length64 >= (uint64_t)INT_MAX, 0L) || RKL_EXPECTED(((searchU16Length64 / 2ULL) + (replacementU16Length64 * 2ULL)) >= (uint64_t)INT_MAX, 0L))) { *exception = [NSException exceptionWithName:NSRangeException reason:@"Replacement string length exceeds INT_MAX." userInfo:NULL]; goto exitNow; } + + RKLCDelayedAssert((searchU16Length64 < (uint64_t)INT_MAX) && (replacementU16Length64 < (uint64_t)INT_MAX) && (((searchU16Length64 / 2ULL) + (replacementU16Length64 * 2ULL)) < (uint64_t)INT_MAX), exception, exitNow); + + // Zero order approximation of the buffer sizes for holding the replaced string or split strings and split strings pointer offsets. As UTF16 code units. + tempUniCharBufferU16Capacity = (int32_t)(16UL + (searchU16Length + (searchU16Length / 2UL)) + (replacementU16Length * 2UL)); + RKLCDelayedAssert((tempUniCharBufferU16Capacity < INT_MAX) && (tempUniCharBufferU16Capacity > 0), exception, exitNow); + + // Buffer sizes converted from native units to bytes. + size_t stackSize = 0UL, replacementSize = ((size_t)replacementU16Length * sizeof(UniChar)), tempUniCharBufferSize = ((size_t)tempUniCharBufferU16Capacity * sizeof(UniChar)); + + // For the various buffers we require, we first try to allocate from the stack if we're not over the RKL_STACK_LIMIT. If we are, switch to using the heap for the buffer. + if((stackSize + tempUniCharBufferSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((tempUniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)alloca(tempUniCharBufferSize)) == NULL, 0L)) { goto exitNow; } stackSize += tempUniCharBufferSize; } + else { if(RKL_EXPECTED((tempUniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc(&rkl_scratchBuffer[0], tempUniCharBufferSize, 0UL)) == NULL, 0L)) { goto exitNow; } } + + // Try to get the pointer to the replacement strings UTF16 data. If we can't, allocate some buffer space, then covert to UTF16. + if((replacementUniChar = CFStringGetCharactersPtr((CFStringRef)replacementString)) == NULL) { + RKL_STRONG_REF UniChar * RKL_GC_VOLATILE uniCharBuffer = NULL; + if((stackSize + replacementSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((uniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)alloca(replacementSize)) == NULL, 0L)) { goto exitNow; } stackSize += replacementSize; } + else { if(RKL_EXPECTED((uniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc(&rkl_scratchBuffer[1], replacementSize, 0UL)) == NULL, 0L)) { goto exitNow; } } + CFStringGetCharacters((CFStringRef)replacementString, CFMakeRange(0L, replacementU16Length), uniCharBuffer); // Convert to a UTF16 string. + replacementUniChar = uniCharBuffer; + } + + resultU16Length = rkl_replaceAll(cachedRegex, replacementUniChar, (int32_t)replacementU16Length, tempUniCharBuffer, tempUniCharBufferU16Capacity, &replacedCount, &needU16Capacity, exception, status); + RKLCDelayedAssert((resultU16Length <= tempUniCharBufferU16Capacity) && (needU16Capacity >= resultU16Length) && (needU16Capacity >= 0), exception, exitNow); + if(RKL_EXPECTED((needU16Capacity + 4) >= INT_MAX, 0L)) { *exception = [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Replaced string length exceeds INT_MAX." userInfo:NULL]; goto exitNow; } + + if(RKL_EXPECTED(*status == U_BUFFER_OVERFLOW_ERROR, 0L)) { // Our buffer guess(es) were too small. Resize the buffers and try again. + // rkl_replaceAll will turn a status of U_STRING_NOT_TERMINATED_WARNING in to a U_BUFFER_OVERFLOW_ERROR. + // As an extra precaution, we pad out the amount needed by an extra four characters "just in case". + // http://lists.apple.com/archives/Cocoa-dev/2010/Jan/msg01011.html + needU16Capacity += 4; + tempUniCharBufferSize = ((size_t)(tempUniCharBufferU16Capacity = needU16Capacity + 4) * sizeof(UniChar)); // Use needU16Capacity. Bug 2890810. + if((stackSize + tempUniCharBufferSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((tempUniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)alloca(tempUniCharBufferSize)) == NULL, 0L)) { goto exitNow; } stackSize += tempUniCharBufferSize; } // Warning about stackSize can be safely ignored. + else { if(RKL_EXPECTED((tempUniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc(&rkl_scratchBuffer[0], tempUniCharBufferSize, 0UL)) == NULL, 0L)) { goto exitNow; } } + + *status = U_ZERO_ERROR; // Make sure the status var is cleared and try again. + resultU16Length = rkl_replaceAll(cachedRegex, replacementUniChar, (int32_t)replacementU16Length, tempUniCharBuffer, tempUniCharBufferU16Capacity, &replacedCount, &needU16Capacity, exception, status); + RKLCDelayedAssert((resultU16Length <= tempUniCharBufferU16Capacity) && (needU16Capacity >= resultU16Length) && (needU16Capacity >= 0), exception, exitNow); + } + + // If status != U_ZERO_ERROR, consider it an error, even though status < U_ZERO_ERROR is a 'warning' in ICU nomenclature. + // http://sourceforge.net/tracker/?func=detail&atid=990188&aid=2890810&group_id=204582 + if(RKL_EXPECTED(*status != U_ZERO_ERROR, 0L)) { goto exitNow; } // Something went wrong. + + RKLCDelayedAssert((replacedCount >= 0L), exception, exitNow); + if(RKL_EXPECTED(resultU16Length == 0, 0L)) { resultObject = @""; } // Optimize the case where the replaced text length == 0 with a @"" string. + else if(RKL_EXPECTED((NSUInteger)resultU16Length == searchU16Length, 0L) && RKL_EXPECTED(replacedCount == 0L, 1L)) { // Optimize the case where the replacement == original by creating a copy. Very fast if self is immutable. + if(replaceMutable == 0UL) { resultObject = rkl_CFAutorelease(CFStringCreateCopy(NULL, (CFStringRef)searchString)); } // .. but only if this is not replacing a mutable self. Warning about potential leak can be safely ignored. + } else { resultObject = rkl_CFAutorelease(CFStringCreateWithCharacters(NULL, tempUniCharBuffer, (CFIndex)resultU16Length)); } // otherwise, create a new string. Warning about potential leak can be safely ignored. + + // If replaceMutable == 1UL, we don't do the replacement here. We wait until after we return and unlock the cache lock. + // This is because we may be trying to mutate an immutable string object. + if((replaceMutable == 1UL) && RKL_EXPECTED(replacedCount > 0L, 1L)) { // We're working on a mutable string and there were successful matches with replaced text, so there's work to do. + if(cachedRegex->buffer != NULL) { rkl_clearBuffer(cachedRegex->buffer, 0UL); cachedRegex->buffer = NULL; } + NSUInteger idx = 0UL; + for(idx = 0UL; idx < _RKL_LRU_CACHE_SET_WAYS; idx++) { + RKLBuffer *buffer = ((NSUInteger)cachedRegex->setToLength < _RKL_FIXED_LENGTH) ? &rkl_lruFixedBuffer[idx] : &rkl_lruDynamicBuffer[idx]; + if(RKL_EXPECTED(cachedRegex->setToString == buffer->string, 0L) && (cachedRegex->setToLength == buffer->length) && (cachedRegex->setToHash == buffer->hash)) { rkl_clearBuffer(buffer, 0UL); } + } + rkl_clearCachedRegexSetTo(cachedRegex); // Flush any cached information about this string since it will mutate. + } + +exitNow: + if(RKL_EXPECTED(status == NULL, 0L) || RKL_EXPECTED(*status != U_ZERO_ERROR, 0L) || RKL_EXPECTED(exception == NULL, 0L) || RKL_EXPECTED(*exception != NULL, 0L)) { replacedCount = -1L; } + if(rkl_scratchBuffer[0] != NULL) { rkl_scratchBuffer[0] = rkl_free(&rkl_scratchBuffer[0]); } + if(rkl_scratchBuffer[1] != NULL) { rkl_scratchBuffer[1] = rkl_free(&rkl_scratchBuffer[1]); } + if(replacedCountPtr != NULL) { *replacedCountPtr = replacedCount; } + return(resultObject); +} // The two warnings about potential leaks can be safely ignored. + +// IMPORTANT! Should only be called from rkl_replaceString(). +// ---------- +// Modified version of the ICU libraries uregex_replaceAll() that keeps count of the number of replacements made. + +static int32_t rkl_replaceAll(RKLCachedRegex *cachedRegex, RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE replacementUniChar, int32_t replacementU16Length, UniChar *replacedUniChar, int32_t replacedU16Capacity, NSInteger *replacedCount, int32_t *needU16Capacity, id *exception RKL_UNUSED_ASSERTION_ARG, int32_t *status) { + int32_t u16Length = 0, initialReplacedU16Capacity = replacedU16Capacity; + NSUInteger bufferOverflowed = 0UL; + NSInteger replaced = -1L; + RKLCDelayedAssert((cachedRegex != NULL) && (replacementUniChar != NULL) && (replacedUniChar != NULL) && (replacedCount != NULL) && (needU16Capacity != NULL) && (status != NULL) && (replacementU16Length >= 0) && (replacedU16Capacity >= 0), exception, exitNow); + + cachedRegex->lastFindRange = cachedRegex->lastMatchRange = NSNotFoundRange; // Clear the cached find information for this regex so a subsequent find works correctly. + RKL_ICU_FUNCTION_APPEND(uregex_reset)(cachedRegex->icu_regex, 0, status); + + // Work around for ICU uregex_reset() bug, see http://bugs.icu-project.org/trac/ticket/6545 + // http://sourceforge.net/tracker/index.php?func=detail&aid=2105213&group_id=204582&atid=990188 + if(RKL_EXPECTED(cachedRegex->setToRange.length == 0UL, 0L) && (*status == U_INDEX_OUTOFBOUNDS_ERROR)) { *status = U_ZERO_ERROR; } + replaced = 0L; + // This loop originally came from ICU source/i18n/uregex.cpp, uregex_replaceAll. + // There is a bug in that code which causes the size of the buffer required for the replaced text to not be calculated correctly. + // This contains a work around using the variable bufferOverflowed. + // ICU bug: http://bugs.icu-project.org/trac/ticket/6656 + // http://sourceforge.net/tracker/index.php?func=detail&aid=2408447&group_id=204582&atid=990188 + while(RKL_ICU_FUNCTION_APPEND(uregex_findNext)(cachedRegex->icu_regex, status)) { + replaced++; + u16Length += RKL_ICU_FUNCTION_APPEND(uregex_appendReplacement)(cachedRegex->icu_regex, replacementUniChar, replacementU16Length, &replacedUniChar, &replacedU16Capacity, status); + if(RKL_EXPECTED(*status == U_BUFFER_OVERFLOW_ERROR, 0L)) { bufferOverflowed = 1UL; *status = U_ZERO_ERROR; } + } + if(RKL_EXPECTED(*status == U_BUFFER_OVERFLOW_ERROR, 0L)) { bufferOverflowed = 1UL; *status = U_ZERO_ERROR; } + if(RKL_EXPECTED(*status <= U_ZERO_ERROR, 1L)) { u16Length += RKL_ICU_FUNCTION_APPEND(uregex_appendTail)(cachedRegex->icu_regex, &replacedUniChar, &replacedU16Capacity, status); } + + // Try to work around a status of U_STRING_NOT_TERMINATED_WARNING. For now, we treat it as a "Buffer Overflow" error. + // As an extra precaution, in rkl_replaceString, we pad out the amount needed by an extra four characters "just in case". + // http://lists.apple.com/archives/Cocoa-dev/2010/Jan/msg01011.html + if(RKL_EXPECTED(*status == U_STRING_NOT_TERMINATED_WARNING, 0L)) { *status = U_BUFFER_OVERFLOW_ERROR; } + + // Check for status <= U_ZERO_ERROR (a 'warning' in ICU nomenclature) rather than just status == U_ZERO_ERROR. + // Under just the right circumstances, status might be equal to U_STRING_NOT_TERMINATED_WARNING. When this occurred, + // rkl_replaceString would never get the U_BUFFER_OVERFLOW_ERROR status, and thus never grow the buffer to the size needed. + // http://sourceforge.net/tracker/?func=detail&atid=990188&aid=2890810&group_id=204582 + if(RKL_EXPECTED(bufferOverflowed == 1UL, 0L) && RKL_EXPECTED(*status <= U_ZERO_ERROR, 1L)) { *status = U_BUFFER_OVERFLOW_ERROR; } + +#ifndef NS_BLOCK_ASSERTIONS +exitNow: +#endif // NS_BLOCK_ASSERTIONS + if(RKL_EXPECTED(replacedCount != NULL, 1L)) { *replacedCount = replaced; } + if(RKL_EXPECTED(needU16Capacity != NULL, 1L)) { *needU16Capacity = u16Length; } // Use needU16Capacity to return the number of characters that are needed for the completely replaced string. Bug 2890810. + return(initialReplacedU16Capacity - replacedU16Capacity); // Return the number of characters of replacedUniChar that were used. +} + +#pragma mark Internal function used to check if a regular expression is valid. + +static NSUInteger rkl_isRegexValid(id self, SEL _cmd, NSString *regex, RKLRegexOptions options, NSInteger *captureCountPtr, NSError **error) { + volatile NSUInteger RKL_CLEANUP(rkl_cleanup_cacheSpinLockStatus) rkl_cacheSpinLockStatus = 0UL; + + RKLCachedRegex *cachedRegex = NULL; + NSUInteger gotCachedRegex = 0UL; + NSInteger captureCount = -1L; + id exception = NULL; + + if((error != NULL) && (*error != NULL)) { *error = NULL; } + if(RKL_EXPECTED(regex == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInvalidArgumentException, @"The regular expression argument is NULL."); } + + OSSpinLockLock(&rkl_cacheSpinLock); + rkl_cacheSpinLockStatus |= RKLLockedCacheSpinLock; + rkl_dtrace_incrementEventID(); + if(RKL_EXPECTED((cachedRegex = rkl_getCachedRegex(regex, options, error, &exception)) != NULL, 1L)) { gotCachedRegex = 1UL; captureCount = cachedRegex->captureCount; } + cachedRegex = NULL; + OSSpinLockUnlock(&rkl_cacheSpinLock); + rkl_cacheSpinLockStatus |= RKLUnlockedCacheSpinLock; // Warning about rkl_cacheSpinLockStatus never being read can be safely ignored. + + if(captureCountPtr != NULL) { *captureCountPtr = captureCount; } + if(RKL_EXPECTED(exception != NULL, 0L)) { rkl_handleDelayedAssert(self, _cmd, exception); } + return(gotCachedRegex); +} + +#pragma mark Functions used for clearing and releasing resources for various internal data structures + +static void rkl_clearStringCache(void) { + RKLCAbortAssert(rkl_cacheSpinLock != (OSSpinLock)0); + rkl_lastCachedRegex = NULL; + NSUInteger x = 0UL; + for(x = 0UL; x < _RKL_SCRATCH_BUFFERS; x++) { if(rkl_scratchBuffer[x] != NULL) { rkl_scratchBuffer[x] = rkl_free(&rkl_scratchBuffer[x]); } } + for(x = 0UL; x < _RKL_REGEX_CACHE_LINES; x++) { rkl_clearCachedRegex(&rkl_cachedRegexes[x]); } + for(x = 0UL; x < _RKL_LRU_CACHE_SET_WAYS; x++) { rkl_clearBuffer(&rkl_lruFixedBuffer[x], 0UL); rkl_clearBuffer(&rkl_lruDynamicBuffer[x], 1UL); } +} + +static void rkl_clearBuffer(RKLBuffer *buffer, NSUInteger freeDynamicBuffer) { + RKLCAbortAssert(buffer != NULL); + if(RKL_EXPECTED(buffer == NULL, 0L)) { return; } + if(RKL_EXPECTED(freeDynamicBuffer == 1UL, 0L) && RKL_EXPECTED(buffer->uniChar != NULL, 1L)) { RKL_STRONG_REF void * RKL_GC_VOLATILE p = (RKL_STRONG_REF void * RKL_GC_VOLATILE)buffer->uniChar; buffer->uniChar = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_free(&p); } + if(RKL_EXPECTED(buffer->string != NULL, 1L)) { CFRelease((CFTypeRef)buffer->string); buffer->string = NULL; } + buffer->length = 0L; + buffer->hash = 0UL; +} + +static void rkl_clearCachedRegex(RKLCachedRegex *cachedRegex) { + RKLCAbortAssert(cachedRegex != NULL); + if(RKL_EXPECTED(cachedRegex == NULL, 0L)) { return; } + rkl_clearCachedRegexSetTo(cachedRegex); + if(rkl_lastCachedRegex == cachedRegex) { rkl_lastCachedRegex = NULL; } + if(cachedRegex->icu_regex != NULL) { RKL_ICU_FUNCTION_APPEND(uregex_close)(cachedRegex->icu_regex); cachedRegex->icu_regex = NULL; cachedRegex->captureCount = -1L; } + if(cachedRegex->regexString != NULL) { CFRelease((CFTypeRef)cachedRegex->regexString); cachedRegex->regexString = NULL; cachedRegex->options = 0U; cachedRegex->regexHash = 0UL; } +} + +static void rkl_clearCachedRegexSetTo(RKLCachedRegex *cachedRegex) { + RKLCAbortAssert(cachedRegex != NULL); + if(RKL_EXPECTED(cachedRegex == NULL, 0L)) { return; } + if(RKL_EXPECTED(cachedRegex->icu_regex != NULL, 1L)) { int32_t status = 0; RKL_ICU_FUNCTION_APPEND(uregex_setText)(cachedRegex->icu_regex, &rkl_emptyUniCharString[0], 0, &status); } + if(RKL_EXPECTED(cachedRegex->setToString != NULL, 1L)) { CFRelease((CFTypeRef)cachedRegex->setToString); cachedRegex->setToString = NULL; } + cachedRegex->lastFindRange = cachedRegex->lastMatchRange = cachedRegex->setToRange = NSNotFoundRange; + cachedRegex->setToIsImmutable = cachedRegex->setToNeedsConversion = 0U; + cachedRegex->setToUniChar = NULL; + cachedRegex->setToHash = 0UL; + cachedRegex->setToLength = 0L; + cachedRegex->buffer = NULL; +} + +#pragma mark Internal functions used to implement NSException and NSError functionality and userInfo NSDictionaries + +// Helps to keep things tidy. +#define addKeyAndObject(objs, keys, i, k, o) ({id _o=(o), _k=(k); if((_o != NULL) && (_k != NULL)) { objs[i] = _o; keys[i] = _k; i++; } }) + +static NSDictionary *rkl_userInfoDictionary(RKLUserInfoOptions userInfoOptions, NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status, NSString *matchString, NSRange matchRange, NSString *replacementString, NSString *replacedString, NSInteger replacedCount, RKLRegexEnumerationOptions enumerationOptions, ...) { + va_list varArgsList; + va_start(varArgsList, enumerationOptions); + if(regexString == NULL) { regexString = @""; } + + id objects[64], keys[64]; + NSUInteger count = 0UL; + + NSString * RKL_GC_VOLATILE errorNameString = [NSString stringWithUTF8String:RKL_ICU_FUNCTION_APPEND(u_errorName)(status)]; + + addKeyAndObject(objects, keys, count, RKLICURegexRegexErrorKey, regexString); + addKeyAndObject(objects, keys, count, RKLICURegexRegexOptionsErrorKey, [NSNumber numberWithUnsignedInt:options]); + addKeyAndObject(objects, keys, count, RKLICURegexErrorCodeErrorKey, [NSNumber numberWithInt:status]); + addKeyAndObject(objects, keys, count, RKLICURegexErrorNameErrorKey, errorNameString); + + if(matchString != NULL) { addKeyAndObject(objects, keys, count, RKLICURegexSubjectStringErrorKey, matchString); } + if((userInfoOptions & RKLUserInfoSubjectRange) != 0UL) { addKeyAndObject(objects, keys, count, RKLICURegexSubjectRangeErrorKey, [NSValue valueWithRange:matchRange]); } + if(replacementString != NULL) { addKeyAndObject(objects, keys, count, RKLICURegexReplacementStringErrorKey, replacementString); } + if(replacedString != NULL) { addKeyAndObject(objects, keys, count, RKLICURegexReplacedStringErrorKey, replacedString); } + if((userInfoOptions & RKLUserInfoReplacedCount) != 0UL) { addKeyAndObject(objects, keys, count, RKLICURegexReplacedCountErrorKey, [NSNumber numberWithInteger:replacedCount]); } + if((userInfoOptions & RKLUserInfoRegexEnumerationOptions) != 0UL) { addKeyAndObject(objects, keys, count, RKLICURegexEnumerationOptionsErrorKey, [NSNumber numberWithUnsignedInteger:enumerationOptions]); } + + if((parseError != NULL) && (parseError->line != -1)) { + NSString *preContextString = [NSString stringWithCharacters:&parseError->preContext[0] length:(NSUInteger)RKL_ICU_FUNCTION_APPEND(u_strlen)(&parseError->preContext[0])]; + NSString *postContextString = [NSString stringWithCharacters:&parseError->postContext[0] length:(NSUInteger)RKL_ICU_FUNCTION_APPEND(u_strlen)(&parseError->postContext[0])]; + + addKeyAndObject(objects, keys, count, RKLICURegexLineErrorKey, [NSNumber numberWithInt:parseError->line]); + addKeyAndObject(objects, keys, count, RKLICURegexOffsetErrorKey, [NSNumber numberWithInt:parseError->offset]); + addKeyAndObject(objects, keys, count, RKLICURegexPreContextErrorKey, preContextString); + addKeyAndObject(objects, keys, count, RKLICURegexPostContextErrorKey, postContextString); + addKeyAndObject(objects, keys, count, @"NSLocalizedFailureReason", ([NSString stringWithFormat:@"The error %@ occurred at line %d, column %d: %@<>%@", errorNameString, parseError->line, parseError->offset, preContextString, postContextString])); + } else { + addKeyAndObject(objects, keys, count, @"NSLocalizedFailureReason", ([NSString stringWithFormat:@"The error %@ occurred.", errorNameString])); + } + + while(count < 62UL) { id obj = va_arg(varArgsList, id), key = va_arg(varArgsList, id); if((obj != NULL) && (key != NULL)) { addKeyAndObject(objects, keys, count, key, obj); } else { break; } } + va_end(varArgsList); + + return([NSDictionary dictionaryWithObjects:&objects[0] forKeys:&keys[0] count:count]); +} + +static NSError *rkl_makeNSError(RKLUserInfoOptions userInfoOptions, NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status, NSString *matchString, NSRange matchRange, NSString *replacementString, NSString *replacedString, NSInteger replacedCount, RKLRegexEnumerationOptions enumerationOptions, NSString *errorDescription) { + if(errorDescription == NULL) { errorDescription = (status == U_ZERO_ERROR) ? @"No description of this error is available." : [NSString stringWithFormat:@"ICU regular expression error #%d, %s.", status, RKL_ICU_FUNCTION_APPEND(u_errorName)(status)]; } + return([NSError errorWithDomain:RKLICURegexErrorDomain code:(NSInteger)status userInfo:rkl_userInfoDictionary(userInfoOptions, regexString, options, parseError, status, matchString, matchRange, replacementString, replacedString, replacedCount, enumerationOptions, errorDescription, @"NSLocalizedDescription", NULL)]); +} + +static NSException *rkl_NSExceptionForRegex(NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status) { + return([NSException exceptionWithName:RKLICURegexException reason:[NSString stringWithFormat:@"ICU regular expression error #%d, %s.", status, RKL_ICU_FUNCTION_APPEND(u_errorName)(status)] userInfo:rkl_userInfoDictionary((RKLUserInfoOptions)RKLUserInfoNone, regexString, options, parseError, status, NULL, NSNotFoundRange, NULL, NULL, 0L, (RKLRegexEnumerationOptions)RKLRegexEnumerationNoOptions, NULL)]); +} + +static NSDictionary *rkl_makeAssertDictionary(const char *function, const char *file, int line, NSString *format, ...) { + va_list varArgsList; + va_start(varArgsList, format); + NSString * RKL_GC_VOLATILE formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; + va_end(varArgsList); + NSString * RKL_GC_VOLATILE functionString = [NSString stringWithUTF8String:function], *fileString = [NSString stringWithUTF8String:file]; + return([NSDictionary dictionaryWithObjectsAndKeys:formatString, @"description", functionString, @"function", fileString, @"file", [NSNumber numberWithInt:line], @"line", NSInternalInconsistencyException, @"exceptionName", NULL]); +} + +static NSString *rkl_stringFromClassAndMethod(id object, SEL selector, NSString *format, ...) { + va_list varArgsList; + va_start(varArgsList, format); + NSString * RKL_GC_VOLATILE formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; + va_end(varArgsList); + Class objectsClass = (object == NULL) ? NULL : [object class]; + return([NSString stringWithFormat:@"*** %c[%@ %@]: %@", (object == objectsClass) ? '+' : '-', (objectsClass == NULL) ? @"" : NSStringFromClass(objectsClass), (selector == NULL) ? @":NULL:" : NSStringFromSelector(selector), formatString]); +} + +#ifdef _RKL_BLOCKS_ENABLED + +//////////// +#pragma mark - +#pragma mark Objective-C ^Blocks Support +#pragma mark - +//////////// + +// Prototypes + +static id rkl_performEnumerationUsingBlock(id self, SEL _cmd, + RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, + id matchString, NSRange matchRange, + RKLBlockEnumerationOp blockEnumerationOp, RKLRegexEnumerationOptions enumerationOptions, + NSInteger *replacedCountPtr, NSUInteger *errorFreePtr, + NSError **error, + void (^stringsAndRangesBlock)(NSInteger capturedCount, NSString * const capturedStrings[capturedCount], const NSRange capturedStringRanges[capturedCount], volatile BOOL * const stop), + NSString *(^replaceStringsAndRangesBlock)(NSInteger capturedCount, NSString * const capturedStrings[capturedCount], const NSRange capturedStringRanges[capturedCount], volatile BOOL * const stop) + ) RKL_NONNULL_ARGS(1,2,4,6); + +// This is an object meant for internal use only. It wraps and abstracts various functionality to simplify ^Blocks support. + +@interface RKLBlockEnumerationHelper : NSObject { + @public + RKLCachedRegex cachedRegex; + RKLBuffer buffer; + RKL_STRONG_REF void * RKL_GC_VOLATILE scratchBuffer[_RKL_SCRATCH_BUFFERS]; + NSUInteger needToFreeBufferUniChar:1; +} +- (id)initWithRegex:(NSString *)initRegexString options:(RKLRegexOptions)initOptions string:(NSString *)initString range:(NSRange)initRange error:(NSError **)initError; +@end + +@implementation RKLBlockEnumerationHelper + +- (id)initWithRegex:(NSString *)initRegexString options:(RKLRegexOptions)initOptions string:(NSString *)initString range:(NSRange)initRange error:(NSError **)initError +{ + volatile NSUInteger RKL_CLEANUP(rkl_cleanup_cacheSpinLockStatus) rkl_cacheSpinLockStatus = 0UL; + + int32_t status = U_ZERO_ERROR; + id exception = NULL; + RKLCachedRegex *retrievedCachedRegex = NULL; + +#ifdef _RKL_DTRACE_ENABLED + NSUInteger thisDTraceEventID = 0UL; + unsigned int lookupResultFlags = 0U; +#endif + + if(RKL_EXPECTED((self = [super init]) == NULL, 0L)) { goto errorExit; } + + RKLCDelayedAssert((initRegexString != NULL) && (initString != NULL), &exception, errorExit); + + // IMPORTANT! Once we have obtained the lock, code MUST exit via 'goto exitNow;' to unlock the lock! NO EXCEPTIONS! + // ---------- + OSSpinLockLock(&rkl_cacheSpinLock); // Grab the lock and get cache entry. + rkl_cacheSpinLockStatus |= RKLLockedCacheSpinLock; + rkl_dtrace_incrementAndGetEventID(thisDTraceEventID); + + if(RKL_EXPECTED((retrievedCachedRegex = rkl_getCachedRegex(initRegexString, initOptions, initError, &exception)) == NULL, 0L)) { goto exitNow; } + RKLCDelayedAssert(((retrievedCachedRegex >= rkl_cachedRegexes) && ((retrievedCachedRegex - &rkl_cachedRegexes[0]) < (ssize_t)_RKL_REGEX_CACHE_LINES)) && (retrievedCachedRegex != NULL) && (retrievedCachedRegex->icu_regex != NULL) && (retrievedCachedRegex->regexString != NULL) && (retrievedCachedRegex->captureCount >= 0L) && (retrievedCachedRegex == rkl_lastCachedRegex), &exception, exitNow); + + if(RKL_EXPECTED(retrievedCachedRegex == NULL, 0L) || RKL_EXPECTED(status > U_ZERO_ERROR, 0L) || RKL_EXPECTED(exception != NULL, 0L)) { goto exitNow; } + + if(RKL_EXPECTED((cachedRegex.icu_regex = RKL_ICU_FUNCTION_APPEND(uregex_clone)(retrievedCachedRegex->icu_regex, &status)) == NULL, 0L) || RKL_EXPECTED(status != U_ZERO_ERROR, 0L)) { goto exitNow; } + if(RKL_EXPECTED((cachedRegex.regexString = (CFStringRef)CFRetain((CFTypeRef)retrievedCachedRegex->regexString)) == NULL, 0L)) { goto exitNow; } + cachedRegex.options = initOptions; + cachedRegex.captureCount = retrievedCachedRegex->captureCount; + cachedRegex.regexHash = retrievedCachedRegex->regexHash; + + RKLCDelayedAssert((cachedRegex.icu_regex != NULL) && (cachedRegex.regexString != NULL) && (cachedRegex.captureCount >= 0L), &exception, exitNow); + +exitNow: + if((rkl_cacheSpinLockStatus & RKLLockedCacheSpinLock) != 0UL) { // In case we arrive at exitNow: without obtaining the rkl_cacheSpinLock. + OSSpinLockUnlock(&rkl_cacheSpinLock); + rkl_cacheSpinLockStatus |= RKLUnlockedCacheSpinLock; // Warning about rkl_cacheSpinLockStatus never being read can be safely ignored. + } + + if(RKL_EXPECTED(self == NULL, 0L) || RKL_EXPECTED(retrievedCachedRegex == NULL, 0L) || RKL_EXPECTED(cachedRegex.icu_regex == NULL, 0L) || RKL_EXPECTED(status != U_ZERO_ERROR, 0L) || RKL_EXPECTED(exception != NULL, 0L)) { goto errorExit; } + retrievedCachedRegex = NULL; // Since we no longer hold the lock, ensure that nothing accesses the retrieved cache regex after this point. + + rkl_dtrace_addLookupFlag(lookupResultFlags, RKLEnumerationBufferLookupFlag); + + if(RKL_EXPECTED((buffer.string = CFStringCreateCopy(NULL, (CFStringRef)initString)) == NULL, 0L)) { goto errorExit; } + buffer.hash = CFHash((CFTypeRef)buffer.string); + buffer.length = CFStringGetLength(buffer.string); + + if((buffer.uniChar = (UniChar *)CFStringGetCharactersPtr(buffer.string)) == NULL) { + rkl_dtrace_addLookupFlag(lookupResultFlags, RKLConversionRequiredLookupFlag); + if(RKL_EXPECTED((buffer.uniChar = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc((RKL_STRONG_REF void ** RKL_GC_VOLATILE)&buffer.uniChar, ((size_t)buffer.length * sizeof(UniChar)), 0UL)) == NULL, 0L)) { goto errorExit; } // Resize the buffer. + needToFreeBufferUniChar = rkl_collectingEnabled() ? 0U : 1U; + CFStringGetCharacters(buffer.string, CFMakeRange(0L, buffer.length), (UniChar *)buffer.uniChar); // Convert to a UTF16 string. + } + + if(RKL_EXPECTED((cachedRegex.setToString = (CFStringRef)CFRetain((CFTypeRef)buffer.string)) == NULL, 0L)) { goto errorExit; } + cachedRegex.setToHash = buffer.hash; + cachedRegex.setToLength = buffer.length; + cachedRegex.setToUniChar = buffer.uniChar; + cachedRegex.buffer = &buffer; + + RKLCDelayedAssert((cachedRegex.icu_regex != NULL) && (cachedRegex.setToUniChar != NULL) && (cachedRegex.setToLength < INT_MAX) && (NSMaxRange(initRange) <= (NSUInteger)cachedRegex.setToLength) && (NSMaxRange(initRange) < INT_MAX), &exception, errorExit); + cachedRegex.lastFindRange = cachedRegex.lastMatchRange = NSNotFoundRange; + cachedRegex.setToRange = initRange; + RKL_ICU_FUNCTION_APPEND(uregex_setText)(cachedRegex.icu_regex, cachedRegex.setToUniChar + cachedRegex.setToRange.location, (int32_t)cachedRegex.setToRange.length, &status); + if(RKL_EXPECTED(status > U_ZERO_ERROR, 0L)) { goto errorExit; } + + rkl_dtrace_addLookupFlag(lookupResultFlags, RKLSetTextLookupFlag); + rkl_dtrace_utf16ConversionCacheWithEventID(thisDTraceEventID, lookupResultFlags, initString, cachedRegex.setToRange.location, cachedRegex.setToRange.length, cachedRegex.setToLength); + + return(self); + +errorExit: + if(RKL_EXPECTED(self != NULL, 1L)) { [self autorelease]; } + if(RKL_EXPECTED(status > U_ZERO_ERROR, 0L) && RKL_EXPECTED(exception == NULL, 0L)) { exception = rkl_NSExceptionForRegex(initRegexString, initOptions, NULL, status); } // If we had a problem, prepare an exception to be thrown. + if(RKL_EXPECTED(status < U_ZERO_ERROR, 0L) && (initError != NULL)) { *initError = rkl_makeNSError((RKLUserInfoOptions)RKLUserInfoNone, initRegexString, initOptions, NULL, status, initString, initRange, NULL, NULL, 0L, (RKLRegexEnumerationOptions)RKLRegexEnumerationNoOptions, @"The ICU library returned an unexpected error."); } + if(RKL_EXPECTED(exception != NULL, 0L)) { rkl_handleDelayedAssert(self, _cmd, exception); } + + return(NULL); +} + +#ifdef __OBJC_GC__ +- (void)finalize +{ + rkl_clearCachedRegex(&cachedRegex); + rkl_clearBuffer(&buffer, (needToFreeBufferUniChar != 0U) ? 1LU : 0LU); + NSUInteger tmpIdx = 0UL; // The rkl_free() below is "probably" a no-op when GC is on, but better to be safe than sorry... + for(tmpIdx = 0UL; tmpIdx < _RKL_SCRATCH_BUFFERS; tmpIdx++) { if(RKL_EXPECTED(scratchBuffer[tmpIdx] != NULL, 0L)) { scratchBuffer[tmpIdx] = rkl_free(&scratchBuffer[tmpIdx]); } } + [super finalize]; +} +#endif // __OBJC_GC__ + +- (void)dealloc +{ + rkl_clearCachedRegex(&cachedRegex); + rkl_clearBuffer(&buffer, (needToFreeBufferUniChar != 0U) ? 1LU : 0LU); + NSUInteger tmpIdx = 0UL; + for(tmpIdx = 0UL; tmpIdx < _RKL_SCRATCH_BUFFERS; tmpIdx++) { if(RKL_EXPECTED(scratchBuffer[tmpIdx] != NULL, 0L)) { scratchBuffer[tmpIdx] = rkl_free(&scratchBuffer[tmpIdx]); } } + [super dealloc]; +} + +@end + +// IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. +// ---------- +// +// Return value: BOOL. Per "Error Handling Programming Guide" wrt/ NSError, return NO on error / failure, and set *error to an NSError object. +// +// rkl_performEnumerationUsingBlock reference counted / manual memory management notes: +// +// When running using reference counting, rkl_performEnumerationUsingBlock() creates a CFMutableArray called autoreleaseArray, which is -autoreleased. +// autoreleaseArray uses the rkl_transferOwnershipArrayCallBacks CFArray callbacks which do not perform a -retain/CFRetain() when objects are added, but do perform a -release/CFRelease() when an object is removed. +// +// A special class, RKLBlockEnumerationHelper, is used to manage the details of creating a private instantiation of the ICU regex (via uregex_clone()) and setting up the details of the UTF-16 buffer required by the ICU regex engine. +// The instantiated RKLBlockEnumerationHelper is not autoreleased, but added to autoreleaseArray. When rkl_performEnumerationUsingBlock() exits, it calls CFArrayRemoveAllValues(autoreleaseArray), which empties the array. +// This has the effect of immediately -releasing the instantiated RKLBlockEnumerationHelper object, and all the memory used to hold the ICU regex and UTF-16 conversion buffer. +// This means the memory is reclaimed immediately and we do not have to wait until the autorelease pool pops. +// +// If we are performing a "string replacement" operation, we create a temporary NSMutableString named mutableReplacementString to hold the replaced strings results. mutableReplacementString is also added to autoreleaseArray so that it +// can be properly released on an error. +// +// Temporary strings that are created during the enumeration of matches are added to autoreleaseArray. +// The strings are added by doing a CFArrayReplaceValues(), which simultaneously releases the previous iterations temporary strings while adding the current iterations temporary strings to the array. +// +// autoreleaseArray always has a reference to any "live" and in use objects. If anything "Goes Wrong", at any point, for any reason (ie, exception is thrown), autoreleaseArray is in the current NSAutoreleasePool +// and will automatically be released when that pool pops. This ensures that we don't leak anything even when things go seriously sideways. This also allows us to keep the total amount of memory in use +// down to a minimum, which can be substantial if the user is enumerating a large string, for example a regex of '\w+' on a 500K+ text file. +// +// The only 'caveat' is that the user needs to -retain any strings that they want to use past the point at which their ^block returns. Logically, it is as if the following takes place: +// +// for(eachMatchOfRegexInStringToSearch) { +// NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; +// callUsersBlock(capturedCount, capturedStrings, capturedStringRanges, stop); +// [pool release]; +// } +// +// But in reality, no NSAutoreleasePool is created, it's all slight of hand done via the CFMutableArray autoreleaseArray. +// +// rkl_performEnumerationUsingBlock garbage collected / automatic memory management notes: +// +// When RegexKitLite is built with -fobjc-gc or -fobjc-gc-only, and (in the case of -fobjc-gc) RegexKitLite determines that GC is active at execution time, then rkl_performEnumerationUsingBlock essentially +// skips all of the above reference counted autoreleaseArray stuff. +// +// rkl_performEnumerationUsingBlock and RKLRegexEnumerationReleaseStringReturnedByReplacementBlock notes +// +// Under reference counting, this enumeration option allows the user to return a non-autoreleased string, and then have RegexKitLite send the object a -release message once it's done with it. +// The primary reason to do this is to immediately reclaim the memory used by the string holding the replacement text. +// Just in case the user returns one of the strings we passed via capturedStrings[], we check to see if the string return by the block is any of the strings we created and passed via capturedStrings[]. +// If it is one of our strings, we do not send the string a -release since that would over release it. It is assumed that the user will /NOT/ add a -retain to our strings in this case. +// Under GC, RKLRegexEnumerationReleaseStringReturnedByReplacementBlock is ignored and no -release messages are sent. +// + +#pragma mark Primary internal function that Objective-C ^Blocks related methods call to perform regular expression operations + +static id rkl_performEnumerationUsingBlock(id self, SEL _cmd, + RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, + id matchString, NSRange matchRange, + RKLBlockEnumerationOp blockEnumerationOp, RKLRegexEnumerationOptions enumerationOptions, + NSInteger *replacedCountPtr, NSUInteger *errorFreePtr, + NSError **error, + void (^stringsAndRangesBlock)(NSInteger capturedCount, NSString * const capturedStrings[capturedCount], const NSRange capturedStringRanges[capturedCount], volatile BOOL * const stop), + NSString *(^replaceStringsAndRangesBlock)(NSInteger capturedCount, NSString * const capturedStrings[capturedCount], const NSRange capturedStringRanges[capturedCount], volatile BOOL * const stop)) { + NSMutableArray * RKL_GC_VOLATILE autoreleaseArray = NULL; + RKLBlockEnumerationHelper * RKL_GC_VOLATILE blockEnumerationHelper = NULL; + NSMutableString * RKL_GC_VOLATILE mutableReplacementString = NULL; + RKL_STRONG_REF UniChar * RKL_GC_VOLATILE blockEnumerationHelperUniChar = NULL; + NSUInteger errorFree = NO; + id exception = NULL, returnObject = NULL; + CFRange autoreleaseReplaceRange = CFMakeRange(0L, 0L); + int32_t status = U_ZERO_ERROR; + RKLRegexOp maskedRegexOp = (regexOp & RKLMaskOp); + volatile BOOL shouldStop = NO; + NSInteger replacedCount = -1L; + NSRange lastMatchedRange = NSNotFoundRange; + NSUInteger stringU16Length = 0UL; + + BOOL performStringReplacement = (blockEnumerationOp == RKLBlockEnumerationReplaceOp) ? YES : NO; + + if((error != NULL) && (*error != NULL)) { *error = NULL; } + + if(RKL_EXPECTED(regexString == NULL, 0L)) { exception = (id)RKL_EXCEPTION(NSInvalidArgumentException, @"The regular expression argument is NULL."); goto exitNow; } + if(RKL_EXPECTED(matchString == NULL, 0L)) { exception = (id)RKL_EXCEPTION(NSInternalInconsistencyException, @"The match string argument is NULL."); goto exitNow; } + + if((((enumerationOptions & RKLRegexEnumerationCapturedStringsNotRequired) != 0UL) && ((enumerationOptions & RKLRegexEnumerationFastCapturedStringsXXX) != 0UL)) || + (((enumerationOptions & RKLRegexEnumerationReleaseStringReturnedByReplacementBlock) != 0UL) && (blockEnumerationOp != RKLBlockEnumerationReplaceOp)) || + ((enumerationOptions & (~((RKLRegexEnumerationOptions)(RKLRegexEnumerationCapturedStringsNotRequired | RKLRegexEnumerationReleaseStringReturnedByReplacementBlock | RKLRegexEnumerationFastCapturedStringsXXX)))) != 0UL)) { + exception = (id)RKL_EXCEPTION(NSInvalidArgumentException, @"The RKLRegexEnumerationOptions argument is not valid."); + goto exitNow; + } + + stringU16Length = (NSUInteger)CFStringGetLength((CFStringRef)matchString); + + if(RKL_EXPECTED(matchRange.length == NSUIntegerMax, 1L)) { matchRange.length = stringU16Length; } // For convenience. + if(RKL_EXPECTED(stringU16Length < NSMaxRange(matchRange), 0L)) { exception = (id)RKL_EXCEPTION(NSRangeException, @"Range or index out of bounds."); goto exitNow; } + if(RKL_EXPECTED(stringU16Length >= (NSUInteger)INT_MAX, 0L)) { exception = (id)RKL_EXCEPTION(NSRangeException, @"String length exceeds INT_MAX."); goto exitNow; } + + RKLCDelayedAssert((self != NULL) && (_cmd != NULL) && ((blockEnumerationOp == RKLBlockEnumerationMatchOp) ? (((regexOp == RKLCapturesArrayOp) || (regexOp == RKLSplitOp)) && (stringsAndRangesBlock != NULL) && (replaceStringsAndRangesBlock == NULL)) : 1) && ((blockEnumerationOp == RKLBlockEnumerationReplaceOp) ? ((regexOp == RKLCapturesArrayOp) && (stringsAndRangesBlock == NULL) && (replaceStringsAndRangesBlock != NULL)) : 1) , &exception, exitNow); + + if((rkl_collectingEnabled() == NO) && RKL_EXPECTED((autoreleaseArray = rkl_CFAutorelease(CFArrayCreateMutable(NULL, 0L, &rkl_transferOwnershipArrayCallBacks))) == NULL, 0L)) { goto exitNow; } // Warning about potential leak of Core Foundation object can be safely ignored. + if(RKL_EXPECTED((blockEnumerationHelper = [[RKLBlockEnumerationHelper alloc] initWithRegex:regexString options:options string:matchString range:matchRange error:error]) == NULL, 0L)) { goto exitNow; } // Warning about potential leak of blockEnumerationHelper can be safely ignored. + if(autoreleaseArray != NULL) { CFArrayAppendValue((CFMutableArrayRef)autoreleaseArray, blockEnumerationHelper); autoreleaseReplaceRange.location++; } // We do not autorelease blockEnumerationHelper, but instead add it to autoreleaseArray. + + if(performStringReplacement == YES) { + if(RKL_EXPECTED((mutableReplacementString = [[NSMutableString alloc] init]) == NULL, 0L)) { goto exitNow; } // Warning about potential leak of mutableReplacementString can be safely ignored. + if(autoreleaseArray != NULL) { CFArrayAppendValue((CFMutableArrayRef)autoreleaseArray, mutableReplacementString); autoreleaseReplaceRange.location++; } // We do not autorelease mutableReplacementString, but instead add it to autoreleaseArray. + } + + // RKLBlockEnumerationHelper creates an immutable copy of the string to match (matchString) which we reference via blockEnumerationHelperString. We use blockEnumerationHelperString when creating the captured strings from a match. + // This protects us against the user mutating matchString while we are in the middle of enumerating matches. + NSString * RKL_GC_VOLATILE blockEnumerationHelperString = (NSString *)blockEnumerationHelper->buffer.string, ** RKL_GC_VOLATILE capturedStrings = NULL, *emptyString = @""; + CFMutableStringRef * RKL_GC_VOLATILE fastCapturedStrings = NULL; + NSInteger captureCountBlockArgument = (blockEnumerationHelper->cachedRegex.captureCount + 1L); + size_t capturedStringsCapacity = ((size_t)captureCountBlockArgument + 4UL); + size_t capturedRangesCapacity = (((size_t)captureCountBlockArgument + 4UL) * 5UL); + NSRange *capturedRanges = NULL; + + lastMatchedRange = NSMakeRange(matchRange.location, 0UL); + blockEnumerationHelperUniChar = blockEnumerationHelper->buffer.uniChar; + + RKLCDelayedAssert((blockEnumerationHelperString != NULL) && (blockEnumerationHelperUniChar != NULL) && (captureCountBlockArgument > 0L) && (capturedStringsCapacity > 0UL) && (capturedRangesCapacity > 0UL), &exception, exitNow); + + if((capturedStrings = (NSString ** RKL_GC_VOLATILE)alloca(sizeof(NSString *) * capturedStringsCapacity)) == NULL) { goto exitNow; } // Space to hold the captured strings from a match. + if((capturedRanges = (NSRange *) alloca(sizeof(NSRange) * capturedRangesCapacity)) == NULL) { goto exitNow; } // Space to hold the NSRanges of the captured strings from a match. + +#ifdef NS_BLOCK_ASSERTIONS + { // Initialize the padded capturedStrings and capturedRanges to values that should tickle a fault if they are ever used. + size_t idx = 0UL; + for(idx = captureCountBlockArgument; idx < capturedStringsCapacity; idx++) { capturedStrings[idx] = (NSString *)RKLIllegalPointer; } + for(idx = captureCountBlockArgument; idx < capturedRangesCapacity; idx++) { capturedRanges[idx] = RKLIllegalRange; } + } +#else + { // Initialize all of the capturedStrings and capturedRanges to values that should tickle a fault if they are ever used. + size_t idx = 0UL; + for(idx = 0UL; idx < capturedStringsCapacity; idx++) { capturedStrings[idx] = (NSString *)RKLIllegalPointer; } + for(idx = 0UL; idx < capturedRangesCapacity; idx++) { capturedRanges[idx] = RKLIllegalRange; } + } +#endif + + if((enumerationOptions & RKLRegexEnumerationFastCapturedStringsXXX) != 0UL) { + RKLCDelayedAssert(((enumerationOptions & RKLRegexEnumerationCapturedStringsNotRequired) == 0UL), &exception, exitNow); + size_t idx = 0UL; + if((fastCapturedStrings = (CFMutableStringRef * RKL_GC_VOLATILE)alloca(sizeof(NSString *) * capturedStringsCapacity)) == NULL) { goto exitNow; } // Space to hold the "fast" captured strings from a match. + + for(idx = 0UL; idx < (size_t)captureCountBlockArgument; idx++) { + if((fastCapturedStrings[idx] = CFStringCreateMutableWithExternalCharactersNoCopy(NULL, NULL, 0L, 0L, kCFAllocatorNull)) == NULL) { goto exitNow; } + if(autoreleaseArray != NULL) { CFArrayAppendValue((CFMutableArrayRef)autoreleaseArray, fastCapturedStrings[idx]); autoreleaseReplaceRange.location++; } // We do not autorelease mutableReplacementString, but instead add it to autoreleaseArray. + capturedStrings[idx] = (NSString *)fastCapturedStrings[idx]; + } + } + + RKLFindAll findAll = rkl_makeFindAll(capturedRanges, matchRange, (NSInteger)capturedRangesCapacity, (capturedRangesCapacity * sizeof(NSRange)), 0UL, &blockEnumerationHelper->scratchBuffer[0], &blockEnumerationHelper->scratchBuffer[1], &blockEnumerationHelper->scratchBuffer[2], &blockEnumerationHelper->scratchBuffer[3], &blockEnumerationHelper->scratchBuffer[4], 0L, 0L, 1L); + + NSString ** RKL_GC_VOLATILE capturedStringsBlockArgument = NULL; // capturedStringsBlockArgument is what we pass to the 'capturedStrings[]' argument of the users ^block. Will pass NULL if the user doesn't want the captured strings created automatically. + if((enumerationOptions & RKLRegexEnumerationCapturedStringsNotRequired) == 0UL) { capturedStringsBlockArgument = capturedStrings; } // If the user wants the captured strings automatically created, set to capturedStrings. + + replacedCount = 0L; + while(RKL_EXPECTED(rkl_findRanges(&blockEnumerationHelper->cachedRegex, regexOp, &findAll, &exception, &status) == NO, 1L) && RKL_EXPECTED(findAll.found > 0L, 1L) && RKL_EXPECTED(exception == NULL, 1L) && RKL_EXPECTED(status == U_ZERO_ERROR, 1L)) { + if(performStringReplacement == YES) { + NSUInteger lastMatchedMaxLocation = (lastMatchedRange.location + lastMatchedRange.length); + NSRange previousUnmatchedRange = NSMakeRange(lastMatchedMaxLocation, findAll.ranges[0].location - lastMatchedMaxLocation); + RKLCDelayedAssert((NSMaxRange(previousUnmatchedRange) <= stringU16Length) && (NSRangeInsideRange(previousUnmatchedRange, matchRange) == YES), &exception, exitNow); + if(RKL_EXPECTED(previousUnmatchedRange.length > 0UL, 1L)) { CFStringAppendCharacters((CFMutableStringRef)mutableReplacementString, blockEnumerationHelperUniChar + previousUnmatchedRange.location, (CFIndex)previousUnmatchedRange.length); } + } + + findAll.found -= findAll.addedSplitRanges; + + NSInteger passCaptureCountBlockArgument = ((findAll.found == 0L) && (findAll.addedSplitRanges == 1L) && (maskedRegexOp == RKLSplitOp)) ? 1L : findAll.found, capturedStringsIdx = passCaptureCountBlockArgument; + RKLCDelayedHardAssert(passCaptureCountBlockArgument <= captureCountBlockArgument, &exception, exitNow); + if(capturedStringsBlockArgument != NULL) { // Only create the captured strings if the user has requested them. + BOOL hadError = NO; // Loop over all the strings rkl_findRanges found. If rkl_CreateStringWithSubstring() returns NULL due to an error, set returnBool to NO, and break out of the for() loop. + + for(capturedStringsIdx = 0L; capturedStringsIdx < passCaptureCountBlockArgument; capturedStringsIdx++) { + RKLCDelayedHardAssert(capturedStringsIdx < captureCountBlockArgument, &exception, exitNow); + if((enumerationOptions & RKLRegexEnumerationFastCapturedStringsXXX) != 0UL) { + // Analyzer report of "Dereference of null pointer" can be safely ignored for the next line. Bug filed: http://llvm.org/bugs/show_bug.cgi?id=6150 + CFStringSetExternalCharactersNoCopy(fastCapturedStrings[capturedStringsIdx], &blockEnumerationHelperUniChar[findAll.ranges[capturedStringsIdx].location], (CFIndex)findAll.ranges[capturedStringsIdx].length, (CFIndex)findAll.ranges[capturedStringsIdx].length); + } else { + if((capturedStrings[capturedStringsIdx] = (findAll.ranges[capturedStringsIdx].length == 0UL) ? emptyString : rkl_CreateStringWithSubstring(blockEnumerationHelperString, findAll.ranges[capturedStringsIdx])) == NULL) { hadError = YES; break; } + } + } + if(((enumerationOptions & RKLRegexEnumerationFastCapturedStringsXXX) == 0UL) && RKL_EXPECTED(autoreleaseArray != NULL, 1L)) { CFArrayReplaceValues((CFMutableArrayRef)autoreleaseArray, autoreleaseReplaceRange, (const void **)capturedStrings, capturedStringsIdx); autoreleaseReplaceRange.length = capturedStringsIdx; } // Add to autoreleaseArray all the strings the for() loop created. + if(RKL_EXPECTED(hadError == YES, 0L)) { goto exitNow; } // hadError == YES will be set if rkl_CreateStringWithSubstring() returned NULL. + } + // For safety, set any capturedRanges and capturedStrings up to captureCountBlockArgument + 1 to values that indicate that they are not valid. + // These values are chosen such that they should tickle any misuse by users. + // capturedStringsIdx is initialized to passCaptureCountBlockArgument, but if capturedStringsBlockArgument != NULL, it is reset to 0 by the loop that creates strings. + // If the loop that creates strings has an error, execution should transfer to exitNow and this will never get run. + // Again, this is for safety for users that do not check the passed block argument 'captureCount' and instead depend on something like [regex captureCount]. + for(; capturedStringsIdx < captureCountBlockArgument + 1L; capturedStringsIdx++) { RKLCDelayedAssert((capturedStringsIdx < (NSInteger)capturedStringsCapacity) && (capturedStringsIdx < (NSInteger)capturedRangesCapacity), &exception, exitNow); capturedRanges[capturedStringsIdx] = RKLIllegalRange; capturedStrings[capturedStringsIdx] = (NSString *)RKLIllegalPointer; } + + RKLCDelayedAssert((passCaptureCountBlockArgument > 0L) && (NSMaxRange(capturedRanges[0]) <= stringU16Length) && (capturedRanges[0].location < NSIntegerMax) && (capturedRanges[0].length < NSIntegerMax), &exception, exitNow); + + switch(blockEnumerationOp) { + case RKLBlockEnumerationMatchOp: stringsAndRangesBlock(passCaptureCountBlockArgument, capturedStringsBlockArgument, capturedRanges, &shouldStop); break; + + case RKLBlockEnumerationReplaceOp: { + NSString *blockReturnedReplacementString = replaceStringsAndRangesBlock(passCaptureCountBlockArgument, capturedStringsBlockArgument, capturedRanges, &shouldStop); + + if(RKL_EXPECTED(blockReturnedReplacementString != NULL, 1L)) { + CFStringAppend((CFMutableStringRef)mutableReplacementString, (CFStringRef)blockReturnedReplacementString); + BOOL shouldRelease = (((enumerationOptions & RKLRegexEnumerationReleaseStringReturnedByReplacementBlock) != 0UL) && (capturedStringsBlockArgument != NULL) && (rkl_collectingEnabled() == NO)) ? YES : NO; + if(shouldRelease == YES) { NSInteger idx = 0L; for(idx = 0L; idx < passCaptureCountBlockArgument; idx++) { if(capturedStrings[idx] == blockReturnedReplacementString) { shouldRelease = NO; break; } } } + if(shouldRelease == YES) { [blockReturnedReplacementString release]; } + } + } + break; + + default: exception = RKLCAssertDictionary(@"Unknown blockEnumerationOp code."); goto exitNow; break; + } + + replacedCount++; + findAll.addedSplitRanges = 0L; // rkl_findRanges() expects findAll.addedSplitRanges to be 0 on entry. + findAll.found = 0L; // rkl_findRanges() expects findAll.found to be 0 on entry. + findAll.findInRange = findAll.remainingRange; // Ask rkl_findRanges() to search the part of the string after the current match. + lastMatchedRange = findAll.ranges[0]; + + if(RKL_EXPECTED(shouldStop != NO, 0L)) { break; } + } + errorFree = YES; + +exitNow: + if(RKL_EXPECTED(errorFree == NO, 0L)) { replacedCount = -1L; } + if((blockEnumerationOp == RKLBlockEnumerationReplaceOp) && RKL_EXPECTED(errorFree == YES, 1L)) { + RKLCDelayedAssert(replacedCount >= 0L, &exception, exitNow2); + if(RKL_EXPECTED(replacedCount == 0UL, 0L)) { + RKLCDelayedAssert((blockEnumerationHelper != NULL) && (blockEnumerationHelper->buffer.string != NULL), &exception, exitNow2); + returnObject = rkl_CreateStringWithSubstring((id)blockEnumerationHelper->buffer.string, matchRange); + if(rkl_collectingEnabled() == NO) { returnObject = rkl_CFAutorelease(returnObject); } + } + else { + NSUInteger lastMatchedMaxLocation = (lastMatchedRange.location + lastMatchedRange.length); + NSRange previousUnmatchedRange = NSMakeRange(lastMatchedMaxLocation, NSMaxRange(matchRange) - lastMatchedMaxLocation); + RKLCDelayedAssert((NSMaxRange(previousUnmatchedRange) <= stringU16Length) && (NSRangeInsideRange(previousUnmatchedRange, matchRange) == YES), &exception, exitNow2); + + if(RKL_EXPECTED(previousUnmatchedRange.length > 0UL, 1L)) { CFStringAppendCharacters((CFMutableStringRef)mutableReplacementString, blockEnumerationHelperUniChar + previousUnmatchedRange.location, (CFIndex)previousUnmatchedRange.length); } + returnObject = rkl_CFAutorelease(CFStringCreateCopy(NULL, (CFStringRef)mutableReplacementString)); // Warning about potential leak of Core Foundation object can be safely ignored. + } + } + +#ifndef NS_BLOCK_ASSERTIONS +exitNow2: +#endif // NS_BLOCK_ASSERTIONS + if(RKL_EXPECTED(autoreleaseArray != NULL, 1L)) { CFArrayRemoveAllValues((CFMutableArrayRef)autoreleaseArray); } // Causes blockEnumerationHelper to be released immediately, freeing all of its resources (such as a large UTF-16 conversion buffer). + if(RKL_EXPECTED(exception != NULL, 0L)) { rkl_handleDelayedAssert(self, _cmd, exception); } // If there is an exception, throw it at this point. + if(((errorFree == NO) || ((errorFree == YES) && (returnObject == NULL))) && (error != NULL) && (*error == NULL)) { + RKLUserInfoOptions userInfoOptions = (RKLUserInfoSubjectRange | RKLUserInfoRegexEnumerationOptions); + NSString *replacedString = NULL; + if(blockEnumerationOp == RKLBlockEnumerationReplaceOp) { userInfoOptions |= RKLUserInfoReplacedCount; if(RKL_EXPECTED(errorFree == YES, 1L)) { replacedString = returnObject; } } + *error = rkl_makeNSError(userInfoOptions, regexString, options, NULL, status, (blockEnumerationHelper != NULL) ? (blockEnumerationHelper->buffer.string != NULL) ? (NSString *)blockEnumerationHelper->buffer.string : matchString : matchString, matchRange, NULL, replacedString, replacedCount, enumerationOptions, @"An unexpected error occurred."); + } + if(replacedCountPtr != NULL) { *replacedCountPtr = replacedCount; } + if(errorFreePtr != NULL) { *errorFreePtr = errorFree; } + return(returnObject); +} // The two warnings about potential leaks can be safely ignored. + +#endif // _RKL_BLOCKS_ENABLED + +//////////// +#pragma mark - +#pragma mark Objective-C Public Interface +#pragma mark - +//////////// + +@implementation NSString (RegexKitLiteAdditions) + +#pragma mark +clearStringCache + ++ (void)RKL_METHOD_PREPEND(clearStringCache) +{ + volatile NSUInteger RKL_CLEANUP(rkl_cleanup_cacheSpinLockStatus) rkl_cacheSpinLockStatus = 0UL; + OSSpinLockLock(&rkl_cacheSpinLock); + rkl_cacheSpinLockStatus |= RKLLockedCacheSpinLock; + rkl_clearStringCache(); + OSSpinLockUnlock(&rkl_cacheSpinLock); + rkl_cacheSpinLockStatus |= RKLUnlockedCacheSpinLock; // Warning about rkl_cacheSpinLockStatus never being read can be safely ignored. +} + +#pragma mark +captureCountForRegex: + ++ (NSInteger)RKL_METHOD_PREPEND(captureCountForRegex):(NSString *)regex +{ + NSInteger captureCount = -1L; + rkl_isRegexValid(self, _cmd, regex, RKLNoOptions, &captureCount, NULL); + return(captureCount); +} + ++ (NSInteger)RKL_METHOD_PREPEND(captureCountForRegex):(NSString *)regex options:(RKLRegexOptions)options error:(NSError **)error +{ + NSInteger captureCount = -1L; + rkl_isRegexValid(self, _cmd, regex, options, &captureCount, error); + return(captureCount); +} + +#pragma mark -captureCount: + +- (NSInteger)RKL_METHOD_PREPEND(captureCount) +{ + NSInteger captureCount = -1L; + rkl_isRegexValid(self, _cmd, self, RKLNoOptions, &captureCount, NULL); + return(captureCount); +} + +- (NSInteger)RKL_METHOD_PREPEND(captureCountWithOptions):(RKLRegexOptions)options error:(NSError **)error +{ + NSInteger captureCount = -1L; + rkl_isRegexValid(self, _cmd, self, options, &captureCount, error); + return(captureCount); +} + +#pragma mark -componentsSeparatedByRegex: + +- (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex +{ + NSRange range = NSMaxiumRange; + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLSplitOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex range:(NSRange)range +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLSplitOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLSplitOp, regex, options, 0L, self, &range, NULL, error, NULL, 0UL, NULL, NULL)); +} + +#pragma mark -isMatchedByRegex: + +- (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex +{ + NSRange result = NSNotFoundRange, range = NSMaxiumRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &result, 0UL, NULL, NULL); + return((result.location == (NSUInteger)NSNotFound) ? NO : YES); +} + +- (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex inRange:(NSRange)range +{ + NSRange result = NSNotFoundRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &result, 0UL, NULL, NULL); + return((result.location == (NSUInteger)NSNotFound) ? NO : YES); +} + +- (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error +{ + NSRange result = NSNotFoundRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, options, 0L, self, &range, NULL, error, &result, 0UL, NULL, NULL); + return((result.location == (NSUInteger)NSNotFound) ? NO : YES); +} + +#pragma mark -isRegexValid + +- (BOOL)RKL_METHOD_PREPEND(isRegexValid) +{ + return(rkl_isRegexValid(self, _cmd, self, RKLNoOptions, NULL, NULL) == 1UL ? YES : NO); +} + +- (BOOL)RKL_METHOD_PREPEND(isRegexValidWithOptions):(RKLRegexOptions)options error:(NSError **)error +{ + return(rkl_isRegexValid(self, _cmd, self, options, NULL, error) == 1UL ? YES : NO); +} + +#pragma mark -flushCachedRegexData + +- (void)RKL_METHOD_PREPEND(flushCachedRegexData) +{ + volatile NSUInteger RKL_CLEANUP(rkl_cleanup_cacheSpinLockStatus) rkl_cacheSpinLockStatus = 0UL; + + CFIndex selfLength = CFStringGetLength((CFStringRef)self); + CFHashCode selfHash = CFHash((CFTypeRef)self); + + OSSpinLockLock(&rkl_cacheSpinLock); + rkl_cacheSpinLockStatus |= RKLLockedCacheSpinLock; + rkl_dtrace_incrementEventID(); + + NSUInteger idx; + for(idx = 0UL; idx < _RKL_REGEX_CACHE_LINES; idx++) { + RKLCachedRegex *cachedRegex = &rkl_cachedRegexes[idx]; + if((cachedRegex->setToString != NULL) && ( (cachedRegex->setToString == (CFStringRef)self) || ((cachedRegex->setToLength == selfLength) && (cachedRegex->setToHash == selfHash)) ) ) { rkl_clearCachedRegexSetTo(cachedRegex); } + } + for(idx = 0UL; idx < _RKL_LRU_CACHE_SET_WAYS; idx++) { RKLBuffer *buffer = &rkl_lruFixedBuffer[idx]; if((buffer->string != NULL) && ((buffer->string == (CFStringRef)self) || ((buffer->length == selfLength) && (buffer->hash == selfHash)))) { rkl_clearBuffer(buffer, 0UL); } } + for(idx = 0UL; idx < _RKL_LRU_CACHE_SET_WAYS; idx++) { RKLBuffer *buffer = &rkl_lruDynamicBuffer[idx]; if((buffer->string != NULL) && ((buffer->string == (CFStringRef)self) || ((buffer->length == selfLength) && (buffer->hash == selfHash)))) { rkl_clearBuffer(buffer, 0UL); } } + + OSSpinLockUnlock(&rkl_cacheSpinLock); + rkl_cacheSpinLockStatus |= RKLUnlockedCacheSpinLock; // Warning about rkl_cacheSpinLockStatus never being read can be safely ignored. +} + +#pragma mark -rangeOfRegex: + +- (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex +{ + NSRange result = NSNotFoundRange, range = NSMaxiumRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &result, 0UL, NULL, NULL); + return(result); +} + +- (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex capture:(NSInteger)capture +{ + NSRange result = NSNotFoundRange, range = NSMaxiumRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, capture, self, &range, NULL, NULL, &result, 0UL, NULL, NULL); + return(result); +} + +- (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex inRange:(NSRange)range +{ + NSRange result = NSNotFoundRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &result, 0UL, NULL, NULL); + return(result); +} + +- (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range capture:(NSInteger)capture error:(NSError **)error +{ + NSRange result = NSNotFoundRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, options, capture, self, &range, NULL, error, &result, 0UL, NULL, NULL); + return(result); +} + +#pragma mark -stringByMatching: + +- (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex +{ + NSRange matchedRange = NSNotFoundRange, range = NSMaxiumRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &matchedRange, 0UL, NULL, NULL); + return((matchedRange.location == (NSUInteger)NSNotFound) ? NULL : rkl_CFAutorelease(CFStringCreateWithSubstring(NULL, (CFStringRef)self, CFMakeRange(matchedRange.location, matchedRange.length)))); // Warning about potential leak can be safely ignored. +} // Warning about potential leak can be safely ignored. + +- (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex capture:(NSInteger)capture +{ + NSRange matchedRange = NSNotFoundRange, range = NSMaxiumRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, capture, self, &range, NULL, NULL, &matchedRange, 0UL, NULL, NULL); + return((matchedRange.location == (NSUInteger)NSNotFound) ? NULL : rkl_CFAutorelease(CFStringCreateWithSubstring(NULL, (CFStringRef)self, CFMakeRange(matchedRange.location, matchedRange.length)))); // Warning about potential leak can be safely ignored. +} // Warning about potential leak can be safely ignored. + +- (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex inRange:(NSRange)range +{ + NSRange matchedRange = NSNotFoundRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &matchedRange, 0UL, NULL, NULL); + return((matchedRange.location == (NSUInteger)NSNotFound) ? NULL : rkl_CFAutorelease(CFStringCreateWithSubstring(NULL, (CFStringRef)self, CFMakeRange(matchedRange.location, matchedRange.length)))); // Warning about potential leak can be safely ignored. +} // Warning about potential leak can be safely ignored. + +- (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range capture:(NSInteger)capture error:(NSError **)error +{ + NSRange matchedRange = NSNotFoundRange; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, options, capture, self, &range, NULL, error, &matchedRange, 0UL, NULL, NULL); + return((matchedRange.location == (NSUInteger)NSNotFound) ? NULL : rkl_CFAutorelease(CFStringCreateWithSubstring(NULL, (CFStringRef)self, CFMakeRange(matchedRange.location, matchedRange.length)))); // Warning about potential leak can be safely ignored. +} // Warning about potential leak can be safely ignored. + +#pragma mark -stringByReplacingOccurrencesOfRegex: + +- (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement +{ + NSRange searchRange = NSMaxiumRange; + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLReplaceOp, regex, RKLNoOptions, 0L, self, &searchRange, replacement, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement range:(NSRange)searchRange +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLReplaceOp, regex, RKLNoOptions, 0L, self, &searchRange, replacement, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement options:(RKLRegexOptions)options range:(NSRange)searchRange error:(NSError **)error +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLReplaceOp, regex, options, 0L, self, &searchRange, replacement, error, NULL, 0UL, NULL, NULL)); +} + +#pragma mark -componentsMatchedByRegex: + +- (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex +{ + NSRange searchRange = NSMaxiumRange; + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLArrayOfStringsOp, regex, RKLNoOptions, 0L, self, &searchRange, NULL, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex capture:(NSInteger)capture +{ + NSRange searchRange = NSMaxiumRange; + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLArrayOfStringsOp, regex, RKLNoOptions, capture, self, &searchRange, NULL, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex range:(NSRange)range +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLArrayOfStringsOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range capture:(NSInteger)capture error:(NSError **)error +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLArrayOfStringsOp, regex, options, capture, self, &range, NULL, error, NULL, 0UL, NULL, NULL)); +} + +#pragma mark -captureComponentsMatchedByRegex: + +- (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex +{ + NSRange searchRange = NSMaxiumRange; + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, RKLNoOptions, 0L, self, &searchRange, NULL, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex range:(NSRange)range +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, options, 0L, self, &range, NULL, error, NULL, 0UL, NULL, NULL)); +} + +#pragma mark -arrayOfCaptureComponentsMatchedByRegex: + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex +{ + NSRange searchRange = NSMaxiumRange; + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLArrayOfCapturesOp | RKLSubcapturesArray), regex, RKLNoOptions, 0L, self, &searchRange, NULL, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex range:(NSRange)range +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLArrayOfCapturesOp | RKLSubcapturesArray), regex, RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, 0UL, NULL, NULL)); +} + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLArrayOfCapturesOp | RKLSubcapturesArray), regex, options, 0L, self, &range, NULL, error, NULL, 0UL, NULL, NULL)); +} + +#pragma mark -dictionaryByMatchingRegex: + +- (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex withKeysAndCaptures:(id)firstKey, ... +{ + NSRange searchRange = NSMaxiumRange; + id returnObject = NULL; + va_list varArgsList; + va_start(varArgsList, firstKey); + returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLDictionaryOfCapturesOp, regex, (RKLRegexOptions)RKLNoOptions, 0L, self, &searchRange, NULL, NULL, NULL, firstKey, varArgsList); + va_end(varArgsList); + return(returnObject); +} + +- (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex range:(NSRange)range withKeysAndCaptures:(id)firstKey, ... +{ + id returnObject = NULL; + va_list varArgsList; + va_start(varArgsList, firstKey); + returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLDictionaryOfCapturesOp, regex, (RKLRegexOptions)RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, firstKey, varArgsList); + va_end(varArgsList); + return(returnObject); +} + +- (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeysAndCaptures:(id)firstKey, ... +{ + id returnObject = NULL; + va_list varArgsList; + va_start(varArgsList, firstKey); + returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLDictionaryOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, firstKey, varArgsList); + va_end(varArgsList); + return(returnObject); +} + +- (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withFirstKey:(id)firstKey arguments:(va_list)varArgsList +{ + return(rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLDictionaryOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, firstKey, varArgsList)); +} + +- (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeys:(id *)keys forCaptures:(int *)captures count:(NSUInteger)count +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLDictionaryOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, count, keys, captures)); +} + +#pragma mark -arrayOfDictionariesByMatchingRegex: + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex withKeysAndCaptures:(id)firstKey, ... +{ + NSRange searchRange = NSMaxiumRange; + id returnObject = NULL; + va_list varArgsList; + va_start(varArgsList, firstKey); + returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLArrayOfDictionariesOfCapturesOp, regex, (RKLRegexOptions)RKLNoOptions, 0L, self, &searchRange, NULL, NULL, NULL, firstKey, varArgsList); + va_end(varArgsList); + return(returnObject); +} + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex range:(NSRange)range withKeysAndCaptures:(id)firstKey, ... +{ + id returnObject = NULL; + va_list varArgsList; + va_start(varArgsList, firstKey); + returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLArrayOfDictionariesOfCapturesOp, regex, (RKLRegexOptions)RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, firstKey, varArgsList); + va_end(varArgsList); + return(returnObject); +} + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeysAndCaptures:(id)firstKey, ... +{ + id returnObject = NULL; + va_list varArgsList; + va_start(varArgsList, firstKey); + returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLArrayOfDictionariesOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, firstKey, varArgsList); + va_end(varArgsList); + return(returnObject); +} + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withFirstKey:(id)firstKey arguments:(va_list)varArgsList +{ + return(rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLArrayOfDictionariesOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, firstKey, varArgsList)); +} + +- (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeys:(id *)keys forCaptures:(int *)captures count:(NSUInteger)count +{ + return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLArrayOfDictionariesOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, count, keys, captures)); +} + +#ifdef _RKL_BLOCKS_ENABLED + +//////////// +#pragma mark - +#pragma mark ^Blocks Related NSString Methods + +#pragma mark -enumerateStringsMatchedByRegex:usingBlock: + +- (BOOL)RKL_METHOD_PREPEND(enumerateStringsMatchedByRegex):(NSString *)regex usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block +{ + NSUInteger errorFree = NO; + rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, (RKLRegexOptions)RKLNoOptions, self, NSMaxiumRange, (RKLBlockEnumerationOp)RKLBlockEnumerationMatchOp, 0UL, NULL, &errorFree, NULL, block, NULL); + return(errorFree == NO ? NO : YES); +} + +- (BOOL)RKL_METHOD_PREPEND(enumerateStringsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block +{ + NSUInteger errorFree = NO; + rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, options, self, range, (RKLBlockEnumerationOp)RKLBlockEnumerationMatchOp, enumerationOptions, NULL, &errorFree, error, block, NULL); + return(errorFree == NO ? NO : YES); +} + +#pragma mark -enumerateStringsSeparatedByRegex:usingBlock: + +- (BOOL)RKL_METHOD_PREPEND(enumerateStringsSeparatedByRegex):(NSString *)regex usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block +{ + NSUInteger errorFree = NO; + rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLSplitOp, regex, (RKLRegexOptions)RKLNoOptions, self, NSMaxiumRange, (RKLBlockEnumerationOp)RKLBlockEnumerationMatchOp, 0UL, NULL, &errorFree, NULL, block, NULL); + return(errorFree == NO ? NO : YES); +} + +- (BOOL)RKL_METHOD_PREPEND(enumerateStringsSeparatedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block +{ + NSUInteger errorFree = NO; + rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLSplitOp, regex, options, self, range, (RKLBlockEnumerationOp)RKLBlockEnumerationMatchOp, enumerationOptions, NULL, &errorFree, error, block, NULL); + return(errorFree == NO ? NO : YES); +} + +#pragma mark -stringByReplacingOccurrencesOfRegex:usingBlock: + +- (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block +{ + return(rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, (RKLRegexOptions)RKLNoOptions, self, NSMaxiumRange, (RKLBlockEnumerationOp)RKLBlockEnumerationReplaceOp, 0UL, NULL, NULL, NULL, NULL, block)); +} + +- (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block +{ + return(rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, options, self, range, (RKLBlockEnumerationOp)RKLBlockEnumerationReplaceOp, enumerationOptions, NULL, NULL, error, NULL, block)); +} + +#endif // _RKL_BLOCKS_ENABLED + +@end + +//////////// +#pragma mark - +@implementation NSMutableString (RegexKitLiteAdditions) + +#pragma mark -replaceOccurrencesOfRegex: + +- (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement +{ + NSRange searchRange = NSMaxiumRange; + NSInteger replacedCount = -1L; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLReplaceOp | RKLReplaceMutable), regex, RKLNoOptions, 0L, self, &searchRange, replacement, NULL, (void **)((void *)&replacedCount), 0UL, NULL, NULL); + return(replacedCount); +} + +- (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement range:(NSRange)searchRange +{ + NSInteger replacedCount = -1L; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLReplaceOp | RKLReplaceMutable), regex, RKLNoOptions, 0L, self, &searchRange, replacement, NULL, (void **)((void *)&replacedCount), 0UL, NULL, NULL); + return(replacedCount); +} + +- (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement options:(RKLRegexOptions)options range:(NSRange)searchRange error:(NSError **)error +{ + NSInteger replacedCount = -1L; + rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLReplaceOp | RKLReplaceMutable), regex, options, 0L, self, &searchRange, replacement, error, (void **)((void *)&replacedCount), 0UL, NULL, NULL); + return(replacedCount); +} + +#ifdef _RKL_BLOCKS_ENABLED + +//////////// +#pragma mark - +#pragma mark ^Blocks Related NSMutableString Methods + +#pragma mark -replaceOccurrencesOfRegex:usingBlock: + +- (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block +{ + NSUInteger errorFree = 0UL; + NSInteger replacedCount = -1L; + NSString *replacedString = rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, RKLNoOptions, self, NSMaxiumRange, (RKLBlockEnumerationOp)RKLBlockEnumerationReplaceOp, 0UL, &replacedCount, &errorFree, NULL, NULL, block); + if((errorFree == YES) && (replacedCount > 0L)) { [self replaceCharactersInRange:NSMakeRange(0UL, [self length]) withString:replacedString]; } + return(replacedCount); +} + +- (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block +{ + NSUInteger errorFree = 0UL; + NSInteger replacedCount = -1L; + NSString *replacedString = rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, options, self, range, (RKLBlockEnumerationOp)RKLBlockEnumerationReplaceOp, enumerationOptions, &replacedCount, &errorFree, error, NULL, block); + if((errorFree == YES) && (replacedCount > 0L)) { [self replaceCharactersInRange:range withString:replacedString]; } + return(replacedCount); +} + +#endif // _RKL_BLOCKS_ENABLED + +@end diff --git a/MP42/SBLanguages.h b/MP42/SBLanguages.h new file mode 100644 index 0000000..9e30fa4 --- /dev/null +++ b/MP42/SBLanguages.h @@ -0,0 +1,49 @@ +// +// SBLanguages.h +// Subler +// +// Created by Damiano Galassi on 13/08/12. +// +// + +#import + +typedef struct iso639_lang_t +{ + char * eng_name; /* Description in English */ + char * native_name; /* Description in native language */ + char * iso639_1; /* ISO-639-1 (2 characters) code */ + char * iso639_2; /* ISO-639-2/t (3 character) code */ + char * iso639_2b; /* ISO-639-2/b code (if different from above) */ + short qtLang; /* QT Lang Code */ + +} iso639_lang_t; + +#ifdef __cplusplus +extern "C" { +#endif + /* find language associated with ISO-639-1 language code */ + iso639_lang_t * lang_for_code( int code ); + iso639_lang_t * lang_for_code_s( const char *code ); + + /* find language associated with ISO-639-2 language code */ + iso639_lang_t * lang_for_code2( const char *code2 ); + + /* find language associated with qt language code */ + iso639_lang_t * lang_for_qtcode( short code ); + + /* ISO-639-1 code for language */ + int lang_to_code(const iso639_lang_t *lang); + + iso639_lang_t * lang_for_english( const char * english ); +#ifdef __cplusplus +} +#endif + +@interface SBLanguages : NSObject + ++ (SBLanguages *)defaultManager; +- (NSArray *)languages; ++ (NSString *)iso6391CodeFor:(NSString *)aLanguage; + +@end diff --git a/MP42/SBLanguages.m b/MP42/SBLanguages.m new file mode 100644 index 0000000..489b4ac --- /dev/null +++ b/MP42/SBLanguages.m @@ -0,0 +1,646 @@ +// +// SBLanguages.m +// Subler +// +// Created by Damiano Galassi on 13/08/12. +// +// + +#import "SBLanguages.h" + +#include +#include + +static const iso639_lang_t languages[] = +{ { "Unknown", "", "", "und", "", 32767 }, + { "Abkhazian", "Аҧсуа", "ab", "abk", "", -1 }, + { "Acehnese, Achinese", "Bahsa Acèh", "", "ace", "", -1 }, + { "Acoli", "", "", "ach", "", -1 }, + { "Adangme", "adangbɛ", "", "ada", "", -1 }, + { "Adyghe, Adygei", "адыгэбзэ, адыгабзэ", "", "ady", "", -1 }, + { "Afar", "Qafara", "aa", "aar", "", -1 }, + { "Afrihili", "", "", "afh", "", -1 }, + { "Afrikaans", "Afrikaans", "af", "afr", "", 141 }, + { "Afroasiatic languages", "", "", "afa", "", -1 }, + { "Ainu (Japan)", "アイヌ イタㇰ(イタッㇰ) or ainu itak", "", "ain", "", -1 }, + { "Akan", "", "ak", "aka", "", -1 }, + { "Akkadian", "akkadû, lišānum akkadītum", "", "akk", "", -1 }, + { "Albanian", "Shqip", "sq", "sqi", "alb", 36 }, + { "Aleut", "", "", "ale", "", -1 }, + { "Algonquian languages", "", "", "alg", "", -1 }, + { "Altaic languages", "", "", "tut", "", -1 }, + { "Amharic", "አማርኛ", "am", "amh", "", 85 }, + { "Ancient Greek", "Ἑλληνικά", "", "grc", "", -1 }, + { "Angika", "", "", "anp", "", -1 }, + { "Apache languages", "", "", "apa", "", -1 }, + { "Arabic", "العربية", "ar", "ara", "", 12 }, + { "Aragonese", "Aragonés", "an", "arg", "", -1 }, + { "Arapaho", "Hinóno'eitíít", "", "arp", "", -1 }, + { "Arawak", "", "", "arw", "", -1 }, + { "Armenian", "Հայերեն լեզու", "hy", "hye", "arm", 51 }, + { "Aromanian, Arumanian, Macedo-Romanian", "Armãneashce, Armãneashti, Limba armãneascã", "", "rup", "", -1 }, + { "Artificial languages", "", "", "art", "", -1 }, + { "Assamese", "অসমীয়া", "as", "asm", "", 68 }, + { "Asturian, Bable, Leonese, Asturleonese", "asturianu, Bable, Llionés, Asturllionés", "", "ast", "", -1 }, + { "Athabaskan languages", "", "", "ath", "", -1 }, + { "Australian languages", "", "", "aus", "", -1 }, + { "Austronesian languages", "", "", "map", "", -1 }, + { "Avaric", "авар мацӀ, магӀарул мацӀ", "av", "ava", "", -1 }, + { "Avestan", "avesta", "ae", "ave", "", -1 }, + { "Awadhi", "अवधी", "", "awa", "", -1 }, + { "Aymara", "aymar aru", "ay", "aym", "", 134 }, + { "Azerbaijani", "Azərbaycanca", "az", "aze", "", 49 }, + { "Balinese", "Basa Bali", "", "ban", "", -1 }, + { "Baltic languages", "", "", "bat", "", -1 }, + { "Baluchi", "بلوچی", "", "bal", "", -1 }, + { "Bambara", "bamanankan", "bm", "bam", "", -1 }, + { "Bamileke languages", "", "", "bai", "", -1 }, + { "Banda languages", "", "", "bad", "", -1 }, + { "Bantu languages", "", "", "bnt", "", -1 }, + { "Basa", "ɓasaá", "", "bas", "", -1 }, + { "Bashkir", "башҡорт теле", "ba", "bak", "", -1 }, + { "Basque", "euskara", "eu", "eus", "baq", 129 }, + { "Batak languages", "Hata Batak", "", "btk", "", -1 }, + { "Beja, Bedawiyet", "بداوية", "", "bej", "", -1 }, + { "Belarusian", "Беларуская мова", "be", "bel", "", 46 }, + { "Bemba", "ichiBemba", "", "bem", "", -1 }, + { "Bengali", "বাংলা", "bn", "ben", "", 67 }, + { "Berber languages", "Tamazight / Tamaziɣt", "", "ber", "", -1 }, + { "Bhojpuri", "भोजपुरी", "", "bho", "", -1 }, + { "Bihari languages", "", "bh", "bih", "", -1 }, + { "Bikol", "", "", "bik", "", -1 }, + { "Bini, Edo", "Edo", "", "bin", "", -1 }, + { "Bislama", "Bislama", "bi", "bis", "", -1 }, + { "Blackfoot, Siksika", "siksiká,  ᓱᖽᐧᖿ", "", "bla", "", -1 }, + { "Blin, Bilin", "ብሊና", "", "byn", "", -1 }, + { "Blissymbols, Blissymbolics, Bliss", "", "", "zbl", "", -1 }, + { "Bosnian", "bosanski jezik", "bs", "bos", "", -1 }, + { "Braj", "ब्रज भाषा", "", "bra", "", -1 }, + { "Breton", "brezhoneg", "br", "bre", "", 142 }, + { "Buginese", "ᨅᨔ ᨕᨘᨁᨗ", "", "bug", "", -1 }, + { "Bulgarian", "български език", "bg", "bul", "", 44 }, + { "Buriat", "буряад хэлэн", "", "bua", "", -1 }, + { "Burmese", "မြန်မာစာ", "my", "mya", "bur", 77 }, + { "Caddo", "Hasí:nay", "", "cad", "", -1 }, + { "Catalan, Valencian", "català / valencià", "ca", "cat", "", 130 }, + { "Caucasian languages", "", "", "cau", "", -1 }, + { "Cebuano", "Sinugboanon", "", "ceb", "", -1 }, + { "Celtic languages", "", "", "cel", "", -1 }, + { "Central American Indian languages", "", "", "cai", "", -1 }, + { "Central Khmer", "ភាសាខ្មែរ", "km", "khm", "", 78 }, + { "Chagatai", "جغتای", "", "chg", "", -1 }, + { "Chamic languages", "", "", "cmc", "", -1 }, + { "Chamorro", "Chamoru", "ch", "cha", "", -1 }, + { "Chechen", "нохчийн мотт", "ce", "che", "", -1 }, + { "Cherokee", "ᏣᎳᎩ", "", "chr", "", -1 }, + { "Cheyenne", "Tsêhést", "", "chy", "", -1 }, + { "Chibcha", "", "", "chb", "", -1 }, + { "Chichewa, Chewa, Nyanja", "chiCheŵa, chinyanja", "ny", "nya", "", 92 }, + { "Chinese", "中文 (ZhongWen)", "zh", "zho", "chi", 19 }, + { "Chinook Jargon", "", "", "chn", "", -1 }, + { "Chipewyan, Dene Suline", "Dëne Sųłiné, ᑌᓀᓲᒢᕄᓀ", "", "chp", "", -1 }, + { "Choctaw", "Chahta Anumpa", "", "cho", "", -1 }, + { "Church Slavonic, Church Slavic, Old Church Slavonic, Old Slavonic, Old Bulgarian", "ѩзыкъ словѣньскъ", "cu", "chu", "", -1 }, + { "Chuukese", "", "", "chk", "", -1 }, + { "Chuvash", "чӑваш чӗлхи", "cv", "chv", "", -1 }, + { "Circassian", "Адыгэбзэ", "", "kbd", "", -1 }, + { "Classical Newari, Old Newari, Classical Nepal Bhasa", "", "", "nwc", "", -1 }, + { "Classical Syriac", "", "", "syc", "", -1 }, + { "Coptic", "ⲙⲉⲧⲛ̀ⲣⲉⲙⲛ̀ⲭⲏⲙⲓ", "", "cop", "", -1 }, + { "Cornish", "Kernewek", "kw", "cor", "", -1 }, + { "Corsican", "corsu, lingua corsa", "co", "cos", "", -1 }, + { "Cree", "ᓀᐦᐃᔭᐍᐏᐣ", "cr", "cre", "", -1 }, + { "Creek", "Maskoki, Mvskokē empunakv", "", "mus", "", -1 }, + { "creoles and pidgins", "", "", "crp", "", -1 }, + { "creoles and pidgins, English-based", "", "", "cpe", "", -1 }, + { "creoles and pidgins, French-based", "", "", "cpf", "", -1 }, + { "creoles and pidgins, Portuguese-based", "", "", "cpp", "", -1 }, + { "Crimean Tatar, Crimean Turkish", "qırımtatar tili, къырымтатар тили", "", "crh", "", -1 }, + { "Croatian", "hrvatski jezik", "hr", "hrv", "", 18 }, + { "Cushitic languages", "", "", "cus", "", -1 }, + { "Czech", "čeština (substantive), česky (adverb)", "cs", "ces", "cze", 38 }, + { "Dakota", "Lakhota", "", "dak", "", -1 }, + { "Danish", "dansk", "da", "dan", "", 7 }, + { "Dargwa", "дарган мез", "", "dar", "", -1 }, + { "Delaware", "Lënape", "", "del", "", -1 }, + { "Dinka", "Thuɔŋjäŋ", "", "din", "", -1 }, + { "Divehi, Dhivehi, Maldivian", "ދިވެހިބަސ", "dv", "div", "", -1 }, + { "Dogri", "डोगरी", "", "doi", "", -1 }, + { "Dogrib", "Tłįchǫ", "", "dgr", "", -1 }, + { "Dravidian languages", "", "", "dra", "", -1 }, + { "Duala", "", "", "dua", "", -1 }, + { "Dutch", "Nederlands", "nl", "nld", "dut", 4 }, + { "Dutch, Middle (c. 1050–1350)", "", "", "dum", "", -1 }, + { "Dyula", "Julakan", "", "dyu", "", -1 }, + { "Dzongkha", "རྫོང་ཁ", "dz", "dzo", "", 137 }, + { "Eastern Frisian", "Seeltersk Fräisk, Seeltersk, Fräisk", "", "frs", "", -1 }, + { "Efik", "", "", "efi", "", -1 }, + { "Egyptian (Ancient)", "", "", "egy", "", -1 }, + { "Ekajuk", "", "", "eka", "", -1 }, + { "Elamite", "", "", "elx", "", -1 }, + { "English", "English", "en", "eng", "", 0 }, + { "Erzya", "эрзянь кель", "", "myv", "", -1 }, + { "Esperanto", "Esperanto", "eo", "epo", "", 94 }, + { "Estonian", "eesti keel", "et", "est", "", 27 }, + { "Ewe", "Ɛʋɛgbɛ", "ee", "ewe", "", -1 }, + { "Ewondo", "", "", "ewo", "", -1 }, + { "Fang", "", "", "fan", "", -1 }, + { "Fanti", "", "", "fat", "", -1 }, + { "Faroese", "føroyskt", "fo", "fao", "", 30 }, + { "Fijian", "vosa Vakaviti", "fj", "fij", "", -1 }, + { "Filipino, Pilipino", "Wikang Filipino", "", "fil", "", -1 }, + { "Finnish", "suomi, suomen kieli", "fi", "fin", "", 13 }, + { "Finno-Ugric languages", "", "", "fiu", "", -1 }, + { "Fon", "Fɔngbe", "", "fon", "", -1 }, + { "French", "français, langue française", "fr", "fra", "fre", 1 }, + { "Friulian", "furlan", "", "fur", "", -1 }, + { "Fulah", "Fulfulde, Pulaar, Pular", "ff", "ful", "", -1 }, + { "Ga", "Gã", "", "gaa", "", -1 }, + { "Galibi Carib", "", "", "car", "", -1 }, + { "Galician", "Galego", "gl", "glg", "", 140 }, + { "Ganda", "Luganda", "lg", "lug", "", -1 }, + { "Gayo", "", "", "gay", "", -1 }, + { "Gbaya", "", "", "gba", "", -1 }, + { "Ge'ez", "ግዕዝ", "", "gez", "", -1 }, + { "Georgian", "ქართული ენა (kartuli ena)", "ka", "kat", "geo", 52 }, + { "German", "Deutsch", "de", "deu", "ger", 2 }, + { "Germanic languages", "", "", "gem", "", -1 }, + { "Gilbertese, Kiribati", "taetae ni Kiribati", "", "gil", "", -1 }, + { "Gondi", "Gōndi", "", "gon", "", -1 }, + { "Gorontalo", "", "", "gor", "", -1 }, + { "Gothic", "𐌲𐌿𐍄𐌹𐍃𐌺", "", "got", "", -1 }, + { "Grebo", "", "", "grb", "", -1 }, + { "Greenlandic, Kalaallisut", "kalaallisut, kalaallit oqaasii", "kl", "kal", "", -1 }, + { "Guarani", "Avañe'ẽ", "gn", "grn", "", 133 }, + { "Gujarati", "ગુજરાતી", "gu", "guj", "", 69 }, + { "Gwichʼin", "", "", "gwi", "", -1 }, + { "Haida", "X̲aat Kíl", "", "hai", "", -1 }, + { "Haitian Creole, Haitian", "Kreyòl ayisyen", "ht", "hat", "", -1 }, + { "Hausa", "Hausancī, هَوُسَ", "ha", "hau", "", -1 }, + { "Hawaiian", "‘Ōlelo Hawai‘i", "", "haw", "", -1 }, + { "Hebrew", "עִבְרִית, עברית", "he", "heb", "", 10 }, + { "Herero", "Otjiherero", "hz", "her", "", -1 }, + { "Hiligaynon", "Ilonggo", "", "hil", "", -1 }, + { "Himachali languages", "", "", "him", "", -1 }, + { "Hindi", "हिन्दी", "hi", "hin", "", 21 }, + { "Hiri Motu", "Hiri Motu", "ho", "hmo", "", -1 }, + { "Hittite", "", "", "hit", "", -1 }, + { "Hmong", "Hmoob", "", "hmn", "", -1 }, + { "Hungarian", "magyar", "hu", "hun", "", 26 }, + { "Hupa", "Na:tinixwe Mixine:whe", "", "hup", "", -1 }, + { "Iban", "", "", "iba", "", -1 }, + { "Icelandic", "íslenska", "is", "isl", "ice", 15 }, + { "Ido", "Ido", "io", "ido", "", -1 }, + { "Igbo", "Igbo", "ig", "ibo", "", -1 }, + { "Ijo languages", "", "", "ijo", "", -1 }, + { "Iloko", "", "", "ilo", "", -1 }, + { "Inari Sami", "säämegiella", "", "smn", "", -1 }, + { "Indic languages", "", "", "inc", "", -1 }, + { "Indo-European languages", "", "", "ine", "", -1 }, + { "Indonesian", "Bahasa Indonesia", "id", "ind", "", 81 }, + { "Ingush", "гӀалгӀай мотт", "", "inh", "", -1 }, + { "Interlingua (International Auxiliary Language Association)", "interlingua", "ia", "ina", "", -1 }, + { "Interlingue, Occidental", "Interlingue", "ie", "ile", "", -1 }, + { "Inuktitut", "ᐃᓄᒃᑎᑐᑦ", "iu", "iku", "", 143 }, + { "Inupiaq", "Iñupiaq, Iñupiatun", "ik", "ipk", "", -1 }, + { "Iranian languages", "", "", "ira", "", -1 }, + { "Irish", "Gaeilge", "ga", "gle", "", 35 }, + { "Iroquoian languages", "", "", "iro", "", -1 }, + { "Italian", "italiano", "it", "ita", "", 3 }, + { "Japanese", "日本語 (にほんご)", "ja", "jpn", "", 11 }, + { "Javanese", "basa Jawa (ꦧꦱꦗꦮ)", "jv", "jav", "", 138 }, + { "Judeo-Arabic", "", "", "jrb", "", -1 }, + { "Judæo-Persian", "", "", "jpr", "", -1 }, + { "Kabyle", "Taqbaylit", "", "kab", "", -1 }, + { "Kachin, Jingpho", "Jingpho, Marip", "", "kac", "", -1 }, + { "Kalmyk, Oirat", "хальмг келн", "", "xal", "", -1 }, + { "Kamba", "", "", "kam", "", -1 }, + { "Kannada", "ಕನ್ನಡ", "kn", "kan", "", 73 }, + { "Kanuri", "", "kr", "kau", "", -1 }, + { "Kara-Kalpak", "қарақалпақ тили", "", "kaa", "", -1 }, + { "Karachay-Balkar", "къарачай-малкъар тил", "", "krc", "", -1 }, + { "Karelian", "karjalan kieli", "", "krl", "", -1 }, + { "Karen languages", "", "", "kar", "", -1 }, + { "Kashmiri", "कॉशुर, کٲشُر", "ks", "kas", "", 61 }, + { "Kashubian", "kaszëbsczi jãzëk", "", "csb", "", -1 }, + { "Kawi", "Bhāṣa Kawi", "", "kaw", "", -1 }, + { "Kazakh", "Қазақ тілі", "kk", "kaz", "", 48 }, + { "Khasi", "Khasi", "", "kha", "", -1 }, + { "Khoisan languages", "", "", "khi", "", -1 }, + { "Khotanese, Sakan", "ancient", "", "kho", "", -1 }, + { "Kikuyu, Gikuyu", "Gĩkũyũ", "ki", "kik", "", -1 }, + { "Kimbundu", "", "", "kmb", "", -1 }, + { "Kinyarwanda", "Ikinyarwanda", "rw", "kin", "", 90 }, + { "Kirghiz, Kyrgyz", "кыргыз тили", "ky", "kir", "", 54 }, + { "Klingon", "tlhIngan Hol", "", "tlh", "", -1 }, + { "Komi", "коми кыв", "kv", "kom", "", -1 }, + { "Kongo", "Kikongo", "kg", "kon", "", -1 }, + { "Konkani", "कॊंकणि", "", "kok", "", -1 }, + { "Korean", "한국어 (韓國語), 조선말 (朝鮮語)", "ko", "kor", "", 23 }, + { "Kosraean", "Kosrae", "", "kos", "", -1 }, + { "Kpelle", "kpele", "", "kpe", "", -1 }, + { "Kru languages", "", "", "kro", "", -1 }, + { "Kuanyama, Kwanyama", "", "kj", "kua", "", -1 }, + { "Kumyk", "Кумык", "", "kum", "", -1 }, + { "Kurdish", "Kurdî", "ku", "kur", "", 60 }, + { "Kurukh", "", "", "kru", "", -1 }, + { "Kutenai", "Ktunaxa", "", "kut", "", -1 }, + { "Ladino", "ג'ודיאו-איספאנייול", "", "lad", "", -1 }, + { "Lahnda", "ਲਹਿੰਦੀ", "", "lah", "", -1 }, + { "Lamba", "", "", "lam", "", -1 }, + { "Land Dayak languages", "", "", "day", "", -1 }, + { "Lao", "ພາສາລາວ", "lo", "lao", "", 79 }, + { "Latin", "latine, lingua Latina", "la", "lat", "", 131 }, + { "Latvian", "latviešu valoda", "lv", "lav", "", -1 }, + { "Lezghian", "лезги чӀал", "", "lez", "", -1 }, + { "Limburgish, Limburger, Limburgan", "Limburgs", "li", "lim", "", -1 }, + { "Lingala", "lingala", "ln", "lin", "", -1 }, + { "Lithuanian", "lietuvių kalba", "lt", "lit", "", 24 }, + { "Lojban", "lojban", "", "jbo", "", -1 }, + { "Low German, Low Saxon", "Nederdüütsch, Plattdüütsch", "", "nds", "", -1 }, + { "Lower Sorbian", "dolnoserbski", "", "dsb", "", -1 }, + { "Lozi", "siLozi", "", "loz", "", -1 }, + { "Luba-Katanga", "", "lu", "lub", "", -1 }, + { "Luba-Lulua", "lwaà:", "", "lua", "", -1 }, + { "Luiseño", "", "", "lui", "", -1 }, + { "Lule Sami", "sámegiella", "", "smj", "", -1 }, + { "Lunda", "chiLunda", "", "lun", "", -1 }, + { "Luo (Kenya and Tanzania)", "Dholuo", "", "luo", "", -1 }, + { "Lushai", "", "", "lus", "", -1 }, + { "Luxembourgish, Letzeburgesch", "Lëtzebuergesch", "lb", "ltz", "", -1 }, + { "Maasai", "ɔl Maa", "", "mas", "", -1 }, + { "Macedonian", "македонски јазик", "mk", "mkd", "mac", 43 }, + { "Madurese", "", "", "mad", "", -1 }, + { "Magahi", "", "", "mag", "", -1 }, + { "Maithili", "मैथिली", "", "mai", "", -1 }, + { "Makasar", "", "", "mak", "", -1 }, + { "Malagasy", "Malagasy fiteny", "mg", "mlg", "", 93 }, + { "Malay", "bahasa Melayu, بهاس ملايو", "ms", "msa", "may", 83 }, + { "Malayalam", "മലയാളം", "ml", "mal", "", 72 }, + { "Maltese", "Malti", "mt", "mlt", "", 16 }, + { "Manchu", "ᠮᠠᠨᠵᡠ ᡤᡳᠰᡠᠨ ᠪᡝ", "", "mnc", "", -1 }, + { "Mandar", "", "", "mdr", "", -1 }, + { "Mandingo", "", "", "man", "", -1 }, + { "Manipuri", "মৈইতৈইলোন", "", "mni", "", -1 }, + { "Manobo languages", "", "", "mno", "", -1 }, + { "Manx", "Gaelg, Manninagh", "gv", "glv", "", 145 }, + { "Mapudungun, Mapuche", "mapudungun, mapuchedungun", "", "arn", "", -1 }, + { "Marathi", "मराठी", "mr", "mar", "", 66 }, + { "Mari (Russia)", "марий йылме", "", "chm", "", -1 }, + { "Marshallese", "Kajin M̧ajeļ", "mh", "mah", "", -1 }, + { "Marwari", "मारवाड़ी", "", "mwr", "", -1 }, + { "Mayan languages", "", "", "myn", "", -1 }, + { "Mende", "Mɛnde", "", "men", "", -1 }, + { "Mi'kmaq, Micmac", "Míkmaq, Mi'gmaq", "", "mic", "", -1 }, + { "Middle English (1100–1500)", "English", "", "enm", "", -1 }, + { "Middle French (c. 1400—1600)", "", "", "frm", "", -1 }, + { "Middle High German (ca. 1050–1500)", "diutisk", "", "gmh", "", -1 }, + { "Middle Irish (900–1200)", "Gaoidhealg", "", "mga", "", -1 }, + { "Minangkabau", "Baso Minangkabau", "", "min", "", -1 }, + { "Mirandese", "Lhéngua Mirandesa", "", "mwl", "", -1 }, + { "Modern Greek", "Ελληνικά", "el", "ell", "gre", 14 }, + { "Mohawk", "Kanien’keha", "", "moh", "", -1 }, + { "Moksha", "мокшень кяль", "", "mdf", "", -1 }, + { "Mongo", "", "", "lol", "", -1 }, + { "Mongolian", "монгол хэл", "mn", "mon", "", 57 }, + { "Mon–Khmer languages", "", "", "mkh", "", -1 }, + { "Mossi", "Mòoré", "", "mos", "", -1 }, + { "Munda languages", "", "", "mun", "", -1 }, + { "Māori", "te reo Māori", "mi", "mri", "mao", -1 }, + { "N'Ko", "", "", "nqo", "", -1 }, + { "Nahuatl", "nāhuatl, nawatlahtolli", "", "nah", "", -1 }, + { "Nauruan", "Ekakairũ Naoero", "na", "nau", "", -1 }, + { "Navajo, Navaho", "Diné bizaad, Dinékʼehǰí", "nv", "nav", "", -1 }, + { "Ndonga", "Owambo", "ng", "ndo", "", -1 }, + { "Neapolitan", "napulitano", "", "nap", "", -1 }, + { "Nepal Bhasa, Newari", "Nepal Bhasa", "", "new", "", -1 }, + { "Nepali", "नेपाली", "ne", "nep", "", 64 }, + { "Nias", "", "", "nia", "", -1 }, + { "Niger–Congo languages", "", "", "nic", "", -1 }, + { "Nilo-Saharan languages", "", "", "ssa", "", -1 }, + { "Niuean", "ko e vagahau Niuē, faka-Niue", "", "niu", "", -1 }, + { "Nogai", "ногай тили", "", "nog", "", -1 }, + { "North American Indian languages", "", "", "nai", "", -1 }, + { "Northern Frisian", "", "", "frr", "", -1 }, + { "Northern Ndebele", "isiNdebele", "nd", "nde", "", -1 }, + { "Northern Sami", "sámi, sámegiella", "se", "sme", "", -1 }, + { "Northern Sotho, Pedi, Sepedi", "Sesotho sa Leboa, Sepedi", "", "nso", "", -1 }, + { "Norwegian", "norsk", "no", "nor", "", 9 }, + { "Norwegian Bokmål", "bokmål", "nb", "nob", "", -1 }, + { "Norwegian Nynorsk", "nynorsk", "nn", "nno", "", -1 }, + { "Nubian languages", "", "", "nub", "", -1 }, + { "Nyamwezi", "Kinyamwezi", "", "nym", "", -1 }, + { "Nyankole", "", "", "nyn", "", -1 }, + { "Nyoro", "Runyoro", "", "nyo", "", -1 }, + { "Nzima", "", "", "nzi", "", -1 }, + { "Occitan (1500–)", "Occitan", "oc", "oci", "", -1 }, + { "Official Aramaic, Imperial Aramaic (700 BC–300 BC)", "ܐܪܡܝܐ", "", "arc", "", -1 }, + { "Ojibwa", "ᐊᓂᔑᓇᐯᒧᐏᐣ (Anishinaabemowin)", "oj", "oji", "", -1 }, + { "Old English (c. 450–1100)", "Englisc", "", "ang", "", -1 }, + { "Old French (842—c. 1400)", "", "", "fro", "", -1 }, + { "Old High German (ca. 750–1050)", "diutisc", "", "goh", "", -1 }, + { "Old Irish (to 900)", "Goídelc", "", "sga", "", -1 }, + { "Old Norse", "norskr", "", "non", "", -1 }, + { "Old Persian (ca. 600–400 BC)", "", "", "peo", "", -1 }, + { "Old Provençal, Old Occitan (–1500)", "", "", "pro", "", -1 }, + { "Oriya", "ଓଡ଼ିଆ", "or", "ori", "", 71 }, + { "Oromo", "Afaan Oromoo", "om", "orm", "", 87 }, + { "Osage", "", "", "osa", "", -1 }, + { "Ossetian, Ossetic", "ирон ӕвзаг", "os", "oss", "", -1 }, + { "Otomian languages", "", "", "oto", "", -1 }, + { "Pahlavi, (Middle Persian)", "", "", "pal", "", -1 }, + { "Palauan", "tekoi ra Belau", "", "pau", "", -1 }, + { "Pali", "पालि", "pi", "pli", "", -1 }, + { "Pampanga, Kapampangan", "Kapampangan", "", "pam", "", -1 }, + { "Pangasinan", "", "", "pag", "", -1 }, + { "Papiamento", "Papiamentu", "", "pap", "", -1 }, + { "Papuan languages", "", "", "paa", "", -1 }, + { "Pashto language, Pashto", "پښتو", "ps", "pus", "", 59 }, + { "Persian", "فارسی", "fa", "fas", "per", 31 }, + { "Philippine languages", "", "", "phi", "", -1 }, + { "Phoenician", "", "", "phn", "", -1 }, + { "Pohnpeian", "", "", "pon", "", -1 }, + { "Polish", "polski", "pl", "pol", "", 25 }, + { "Portuguese", "português", "pt", "por", "", 8 }, + { "Prakrit", "", "", "pra", "", 70 }, + { "Punjabi, Panjabi", "ਪੰਜਾਬੀ, پنجابی", "pa", "pan", "", -1 }, + { "Quechua", "Runa Simi, Kichwa", "qu", "que", "", 132 }, + { "Rajasthani", "राजस्थानी", "", "raj", "", -1 }, + { "Rapanui", "rapanui, pepito ote henua", "", "rap", "", -1 }, + { "Rarotongan, Cook Islands Maori", "", "", "rar", "", -1 }, + { "Reserved for local use", "", "", "qaa-qtz", "", -1 }, + { "Romance languages", "", "", "roa", "", -1 }, + { "Romanian", "română", "ro", "ron", "rum", 37 }, + { "Romansh", "rumantsch grischun", "rm", "roh", "", -1 }, + { "Romany", "rromani ćhib, Romani šib, Romanó", "", "rom", "", -1 }, + { "Rundi", "Rundi", "rn", "run", "", 91 }, + { "Russian", "русский язык", "ru", "rus", "", 32 }, + { "Salishan languages", "", "", "sal", "", -1 }, + { "Samaritan Aramaic", "ארמית, ܐܪܡܝܐ", "", "sam", "", -1 }, + { "Sami languages", "", "", "smi", "", 29 }, + { "Samoan", "gagana fa'a Samoa", "sm", "smo", "", -1 }, + { "Sandawe", "", "", "sad", "", -1 }, + { "Sango", "yângâ tî sängö", "sg", "sag", "", -1 }, + { "Sanskrit", "संस्कृतम्", "sa", "san", "", 65 }, + { "Santali", "संथाली", "", "sat", "", -1 }, + { "Sardinian", "sardu", "sc", "srd", "", -1 }, + { "Sasak", "", "", "sas", "", -1 }, + { "Scots", "Scots leid, Lallans", "", "sco", "", -1 }, + { "Scottish Gaelic, Gaelic", "Gàidhlig", "gd", "gla", "", 144 }, + { "Selkup", "шӧльӄумыт әты", "", "sel", "", -1 }, + { "Semitic languages", "", "", "sem", "", -1 }, + { "Serbian", "српски језик, srpski jezik", "sr", "srp", "", 42 }, + { "Serer", "", "", "srr", "", -1 }, + { "Shan", "", "", "shn", "", -1 }, + { "Shona", "chiShona", "sn", "sna", "", -1 }, + { "Sichuan Yi, Nuosu", "ꆇꉙ", "ii", "iii", "", -1 }, + { "Sicilian", "Sicilianu", "", "scn", "", -1 }, + { "Sidamo", "Sidámo 'Afó", "", "sid", "", -1 }, + { "Sign languages", "", "", "sgn", "", -1 }, + { "Sindhi", "سنڌي، سندھی, सिन्धी", "sd", "snd", "", 62 }, + { "Sinhalese, Sinhala", "සිංහල", "si", "sin", "", 76 }, + { "Sino-Tibetan languages", "", "", "sit", "", -1 }, + { "Siouan languages", "", "", "sio", "", -1 }, + { "Skolt Sami", "sääʼmǩiõll", "", "sms", "", -1 }, + { "Slave (Athapascan)", "", "", "den", "", -1 }, + { "Slavic languages", "", "", "sla", "", -1 }, + { "Slovak", "slovenčina", "sk", "slk", "slo", 39 }, + { "Slovenian", "slovenščina", "sl", "slv", "", 40 }, + { "Sogdian", "", "", "sog", "", -1 }, + { "Somali", "Soomaaliga, af Soomaali", "so", "som", "", 88 }, + { "Songhay languages", "", "", "son", "", -1 }, + { "Soninke", "Soninkanxaane", "", "snk", "", -1 }, + { "Sorbian languages", "", "", "wen", "", -1 }, + { "South American Indian languages", "", "", "sai", "", -1 }, + { "Southern Altai", "алтай тили", "", "alt", "", -1 }, + { "Southern Ndebele", "isiNdebele", "nr", "nbl", "", -1 }, + { "Southern Sami", "saemien giele", "", "sma", "", -1 }, + { "Southern Sotho", "Sesotho", "st", "sot", "", -1 }, + { "Spanish", "español, castellano", "es", "spa", "", 6 }, + { "Sranan Tongo", "", "", "srn", "", -1 }, + { "Sukuma", "", "", "suk", "", -1 }, + { "Sumerian", "eme-ĝir", "", "sux", "", -1 }, + { "Sundanese", "basa Sunda", "su", "sun", "", 139 }, + { "Susu", "", "", "sus", "", -1 }, + { "Swahili", "Kiswahili", "sw", "swa", "", 89 }, + { "Swati", "siSwati", "ss", "ssw", "", -1 }, + { "Swedish", "svenska", "sv", "swe", "", 5 }, + { "Swiss German, Alemannic, Alsatian", "Schwyzerdütsch, Alemannisch, Elsassisch", "", "gsw", "", -1 }, + { "Syriac (Northeastern Neo-Aramaic)", "ܣܘܪܝܝܐ", "", "syr", "", -1 }, + { "Tagalog", "Wikang Tagalog, ᜏᜒᜃᜅ᜔ ᜆᜄᜎᜓᜄ᜔", "tl", "tgl", "", 82 }, + { "Tahitian", "te reo Tahiti, te reo Māʼohi", "ty", "tah", "", -1 }, + { "Tai languages", "", "", "tai", "", -1 }, + { "Tajik", "тоҷикӣ, تاجیکی", "tg", "tgk", "", 55 }, + { "Tamashek", "Tamajeq", "", "tmh", "", -1 }, + { "Tamil", "தமிழ்", "ta", "tam", "", 74 }, + { "Tatar", "татарча, tatarça, تاتارچا", "tt", "tat", "", 135 }, + { "Telugu", "తెలుగు", "te", "tel", "", 75 }, + { "Tereno", "", "", "ter", "", -1 }, + { "Tetum", "Tetun", "", "tet", "", -1 }, + { "Thai", "ภาษาไทย", "th", "tha", "", 22 }, + { "Tibetan", "བོད་ཡིག", "bo", "bod", "tib", 63 }, + { "Tigre", "Tigré, Khasa", "", "tig", "", -1 }, + { "Tigrinya", "ትግርኛ", "ti", "tir", "", 86 }, + { "Time", "", "", "tem", "", -1 }, + { "Tiv", "", "", "tiv", "", -1 }, + { "Tlingit", "Lingít", "", "tli", "", -1 }, + { "Tok Pisin", "Tok Pisin", "", "tpi", "", -1 }, + { "Tokelau", "Tokelau", "", "tkl", "", -1 }, + { "Tonga (Nyasa)", "chiTonga", "", "tog", "", -1 }, + { "Tonga (Tonga Islands)", "faka-Tonga", "to", "ton", "", 147 }, + { "Tsimshian", "", "", "tsi", "", -1 }, + { "Tsonga", "Xitsonga", "ts", "tso", "", -1 }, + { "Tswana", "Setswana", "tn", "tsn", "", -1 }, + { "Tumbuka", "chiTumbuka", "", "tum", "", -1 }, + { "Tupian languages", "Nheengatu", "", "tup", "", -1 }, + { "Turkish", "Türkçe", "tr", "tur", "", 17 }, + { "Turkish, Ottoman (1500–1928)", "", "", "ota", "", -1 }, + { "Turkmen", "Түркмен", "tk", "tuk", "", 56 }, + { "Tuvalu", "'gana Tuvalu", "", "tvl", "", -1 }, + { "Tuvinian", "тыва дыл", "", "tyv", "", -1 }, + { "Twi", "", "tw", "twi", "", -1 }, + { "Udmurt", "удмурт кыл", "", "udm", "", -1 }, + { "Ugaritic", "", "", "uga", "", -1 }, + { "Uighur, Uyghur", "Uyƣurqə, Uyğurçe, ئۇيغۇرچ", "ug", "uig", "", 136 }, + { "Ukrainian", "українська мова", "uk", "ukr", "", 45 }, + { "Umbundu", "úmbúndú", "", "umb", "", -1 }, + { "Upper Sorbian", "hornjoserbsce", "", "hsb", "", -1 }, + { "Urdu", "اردو", "ur", "urd", "", 20 }, + { "Uzbek", "O'zbek, Ўзбек, أۇزبېك", "uz", "uzb", "", 47 }, + { "Vai", "", "", "vai", "", -1 }, + { "Venda", "Tshivenḓa", "ve", "ven", "", -1 }, + { "Vietnamese", "Tiếng Việt", "vi", "vie", "", 80 }, + { "Volapük", "Volapük", "vo", "vol", "", -1 }, + { "Votic", "vaďďa tšeeli", "", "vot", "", -1 }, + { "Wakashan languages", "", "", "wak", "", -1 }, + { "Walloon", "walon", "wa", "wln", "", -1 }, + { "Waray-Waray", "Winaray, Lineyte-Samarnon", "", "war", "", -1 }, + { "Washo", "", "", "was", "", -1 }, + { "Welsh", "Cymraeg", "cy", "cym", "wel", 128 }, + { "Western Frisian", "frysk", "fy", "fry", "", -1 }, + { "Wolaytta, Wolaitta", "", "", "wal", "", -1 }, + { "Wolof", "Wolof", "wo", "wol", "", -1 }, + { "Xhosa", "isiXhosa", "xh", "xho", "", -1 }, + { "Yakut", "Саха тыла", "", "sah", "", -1 }, + { "Yao", "Chiyao", "", "yao", "", -1 }, + { "Yapese", "", "", "yap", "", -1 }, + { "Yiddish", "ייִדיש", "yi", "yid", "", 41 }, + { "Yoruba", "Yorùbá", "yo", "yor", "", -1 }, + { "Yupik languages", "", "", "ypk", "", -1 }, + { "Zande languages", "Pazande", "", "znd", "", -1 }, + { "Zapotec", "", "", "zap", "", -1 }, + { "Zaza, Dimili, Dimli, Kirdki, Kirmanjki, Zazaki", "", "", "zza", "", -1 }, + { "Zenaga", "Tuḍḍungiyya", "", "zen", "", -1 }, + { "Zhuang, Chuang", "Saɯ cueŋƅ, Saw cuengh", "za", "zha", "", -1 }, + { "Zulu", "isiZulu", "zu", "zul", "", -1 }, + { "Zuni", "Shiwi", "", "zun", "", -1 }, + { NULL, NULL, NULL, NULL, NULL, -1 } }; + +iso639_lang_t * lang_for_code( int code ) +{ + char code_string[2]; + iso639_lang_t * lang; + + code_string[0] = tolower( ( code >> 8 ) & 0xFF ); + code_string[1] = tolower( code & 0xFF ); + + for( lang = (iso639_lang_t*) languages; lang->eng_name; lang++ ) + { + if( !strncmp( lang->iso639_1, code_string, 2 ) ) + { + return lang; + } + } + + return (iso639_lang_t*) languages; +} + +iso639_lang_t * lang_for_code_s( const char *code ) +{ + char code_string[3]; + iso639_lang_t * lang; + + code_string[0] = tolower( code[0] ); + code_string[1] = tolower( code[1] ); + code_string[2] = 0; + + for( lang = (iso639_lang_t*) languages; lang->eng_name; lang++ ) + { + if( !strncmp( lang->iso639_1, code_string, 2 ) ) + { + return lang; + } + } + + return (iso639_lang_t*) languages; +} + +iso639_lang_t * lang_for_code2( const char *code ) +{ + char code_string[4]; + iso639_lang_t * lang; + + code_string[0] = tolower( code[0] ); + code_string[1] = tolower( code[1] ); + code_string[2] = tolower( code[2] ); + code_string[3] = 0; + + for( lang = (iso639_lang_t*) languages; lang->eng_name; lang++ ) + { + if( !strcmp( lang->iso639_2, code_string ) ) + { + return lang; + } + if( lang->iso639_2b && !strcmp( lang->iso639_2b, code_string ) ) + { + return lang; + } + } + + return (iso639_lang_t*) languages; +} + +iso639_lang_t * lang_for_qtcode( short code ) +{ + iso639_lang_t * lang; + + for( lang = (iso639_lang_t*) languages; lang->eng_name; lang++ ) + { + if( lang->qtLang == code ) + { + return lang; + } + } + + return (iso639_lang_t*) languages; +} + +int lang_to_code(const iso639_lang_t *lang) +{ + int code = 0; + + if (lang) + code = (lang->iso639_1[0] << 8) | lang->iso639_1[1]; + + return code; +} + +iso639_lang_t * lang_for_english( const char * english ) +{ + iso639_lang_t * lang; + + for( lang = (iso639_lang_t*) languages; lang->eng_name; lang++ ) + { + if( !strcmp( lang->eng_name, english ) ) + { + return lang; + } + } + + return (iso639_lang_t*) languages; +} + +@implementation SBLanguages + ++ (SBLanguages *)defaultManager +{ + static dispatch_once_t pred; + static SBLanguages *sharedLanguagesManager = nil; + + dispatch_once(&pred, ^{ sharedLanguagesManager = [[self alloc] init]; }); + return sharedLanguagesManager; +} + +- (NSArray *)languages { + NSMutableArray *languagesArray = [[NSMutableArray alloc] init]; + iso639_lang_t *_languages; + for ( _languages = (iso639_lang_t *) languages; _languages->iso639_2; _languages++ ) + [languagesArray addObject:[NSString stringWithUTF8String:_languages->eng_name]]; + + NSArray *top_languages = [NSArray arrayWithObjects: @"Unknown", @"English", @"French", @"German", @"Italian", @"Dutch", + @"Swedish" , @"Spanish" , @"Danish" , @"Portuguese", @"Norwegian", @"Hebrew", + @"Japanese", @"Arabic", @"Finnish", @"Modern Greek", @"Icelandic", @"Maltese", @"Turkish", + @"Croatian", @"Chinese", @"Urdu", @"Hindi", @"Thai", @"Korean", @"Lithuanian", @"Polish", + @"Hungarian", @"Estonian", @"Latvian", @"Northern Sami", @"Faroese", @"Persian", @"Romanian", @"Russian", + @"Irish", @"Serbian", @"Albanian", @"Bulgarian", @"Czech", @"Slovak", @"Slovenian", nil]; + + [languagesArray removeObjectsInArray:top_languages]; + + for (NSString* lang in [top_languages reverseObjectEnumerator]) { + [languagesArray insertObject:lang atIndex:0]; + } + + return [languagesArray autorelease]; +} + ++ (NSString *)iso6391CodeFor:(NSString *)aLanguage { + iso639_lang_t *_languages; + for ( _languages = (iso639_lang_t*) languages; _languages->iso639_2; _languages++ ) { + if ([[NSString stringWithUTF8String:_languages->eng_name] isEqualToString:aLanguage]) { + return [NSString stringWithUTF8String:_languages->iso639_1]; + } + } + return nil; +} + +@end diff --git a/MP42/SBRatings.h b/MP42/SBRatings.h new file mode 100644 index 0000000..07d6438 --- /dev/null +++ b/MP42/SBRatings.h @@ -0,0 +1,29 @@ +// +// SBRatings.h +// Subler +// +// Created by Douglas Stebila on 2013-06-02. +// +// + +#import + +@interface SBRatings : NSObject { + NSMutableArray *ratingsDictionary; + NSMutableArray *ratings; + NSMutableArray *iTunesCodes; +} + +@property(readonly) NSMutableArray *ratings; +@property(readonly) NSMutableArray *iTunesCodes; + ++ (SBRatings *) defaultManager; + +- (void)updateRatingsCountry; +- (NSArray *) ratingsCountries; + +- (NSUInteger) unknownIndex; +- (NSUInteger) ratingIndexForiTunesCode:(NSString *)aiTunesCode; +- (NSUInteger) ratingIndexForiTunesCountry:(NSString *)aCountry media:(NSString *)aMedia ratingString:(NSString *)aRatingString; + +@end diff --git a/MP42/SBRatings.m b/MP42/SBRatings.m new file mode 100644 index 0000000..a031b86 --- /dev/null +++ b/MP42/SBRatings.m @@ -0,0 +1,127 @@ +// +// SBRatings.m +// Subler +// +// Created by Douglas Stebila on 2013-06-02. +// +// + +#import "SBRatings.h" + +#import "JSONKit.h" + +@implementation SBRatings + +@synthesize ratings; +@synthesize iTunesCodes; + ++ (SBRatings *) defaultManager { + static dispatch_once_t sharedRatingsPred; + static SBRatings *sharedRatingsManager = nil; + dispatch_once(&sharedRatingsPred, ^{ sharedRatingsManager = [[self alloc] init]; }); + return sharedRatingsManager; +} + +- (id) init { + if (self = [super init]) { + NSString* ratingsJSON = [[NSBundle mainBundle] pathForResource:@"Ratings" ofType:@"json"]; + if (!ratingsJSON) { + [self release]; + return nil; + } + + JSONDecoder *jsonDecoder = [JSONDecoder decoder]; + ratingsDictionary = [[jsonDecoder objectWithData:[NSData dataWithContentsOfFile:ratingsJSON]] retain]; + // construct movie ratings + ratings = [[NSMutableArray alloc] init]; + iTunesCodes = [[NSMutableArray alloc] init]; + // if a specific country is picked, include the USA ratings at the end + NSDictionary *usaRatings = nil; + for (NSDictionary *countryRatings in ratingsDictionary) { + NSString *countryName = [countryRatings valueForKey:@"country"]; + if ([countryName isEqualToString:@"USA"]) { + usaRatings = countryRatings; + } + if (![[[NSUserDefaults standardUserDefaults] valueForKey:@"SBRatingsCountry"] isEqualToString:@"All countries"]) { + if (![countryName isEqualToString:@"Unknown"] && ![countryName isEqualToString:[[NSUserDefaults standardUserDefaults] valueForKey:@"SBRatingsCountry"]]) { + continue; + } + + } + for (NSDictionary *rating in [countryRatings valueForKey:@"ratings"]) { + [ratings addObject:[NSString stringWithFormat:@"%@ %@: %@", countryName, [rating valueForKey:@"media"], [rating valueForKey:@"description"]]]; + [iTunesCodes addObject:[NSString stringWithFormat:@"%@|%@|%@|", [rating valueForKey:@"prefix"], [rating valueForKey:@"itunes-code"], [rating valueForKey:@"itunes-value"]]]; + } + } + if (![[[NSUserDefaults standardUserDefaults] valueForKey:@"SBRatingsCountry"] isEqualToString:@"All countries"] && ![[[NSUserDefaults standardUserDefaults] valueForKey:@"SBRatingsCountry"] isEqualToString:@"USA"]) { + if (usaRatings) { + for (NSDictionary *rating in [usaRatings valueForKey:@"ratings"]) { + [ratings addObject:[NSString stringWithFormat:@"%@ %@: %@", @"USA", [rating valueForKey:@"media"], [rating valueForKey:@"description"]]]; + [iTunesCodes addObject:[NSString stringWithFormat:@"%@|%@|%@|", [rating valueForKey:@"prefix"], [rating valueForKey:@"itunes-code"], [rating valueForKey:@"itunes-value"]]]; + } + } + } + } + return self; +} + +- (NSArray *) ratingsCountries { + NSMutableArray *countries = [[NSMutableArray alloc] init]; + for (NSDictionary *countryRatings in ratingsDictionary) { + NSString *countryName = [countryRatings valueForKey:@"country"]; + if ([countryName isEqualToString:@"Unknown"]) { + [countries addObject:@"All countries"]; + } else { + [countries addObject:countryName]; + } + } + return [countries autorelease]; +} + +- (void)updateRatingsCountry { + [ratings release]; + [iTunesCodes release]; + [self init]; +} + +- (NSArray *) ratings { + return [NSArray arrayWithArray:ratings]; +} + +- (NSUInteger) unknownIndex { + return 0; +} + +- (NSUInteger) ratingIndexForiTunesCode:(NSString *)aiTunesCode { + for (int i = 0; i < [iTunesCodes count]; i++) { + if ([[iTunesCodes objectAtIndex:i] isEqualToString:aiTunesCode]) { + return i; + } + } + return [self unknownIndex]; +} + +- (NSUInteger) ratingIndexForiTunesCountry:(NSString *)aCountry media:(NSString *)aMedia ratingString:(NSString *)aRatingString { + NSString *target1 = [[NSString stringWithFormat:@"%@ %@: %@", aCountry, aMedia, aRatingString] lowercaseString]; + NSString *target2 = [[NSString stringWithFormat:@"%@ %@: %@", aCountry, @"movie & TV", aRatingString] lowercaseString]; + for (int i = 0; i < [ratings count]; i++) { + if ([[[ratings objectAtIndex:i] lowercaseString] isEqualToString:target1] || [[[ratings objectAtIndex:i] lowercaseString] isEqualToString:target2]) { + return i; + } + } + if (aRatingString != nil) { + NSLog(@"Unknown rating information: %@", target1); + } + for (NSDictionary *countryRatings in ratingsDictionary) { + if ([[countryRatings valueForKey:@"country"] isEqualToString:aCountry]) { + for (NSDictionary *rating in [countryRatings valueForKey:@"ratings"]) { + if ([[rating valueForKey:@"itunes-value"] isEqualToString:@"???"]) { + return [self ratingIndexForiTunesCode:[NSString stringWithFormat:@"%@|%@|%@|", [rating valueForKey:@"prefix"], [rating valueForKey:@"itunes-code"], [rating valueForKey:@"itunes-value"]]]; + } + } + } + } + return [self unknownIndex]; +} + +@end diff --git a/MP42/muxer/MatroskaFile.c b/MP42/muxer/MatroskaFile.c new file mode 100644 index 0000000..9d43aab --- /dev/null +++ b/MP42/muxer/MatroskaFile.c @@ -0,0 +1,143 @@ +/* + * MatroskaFile.c + * Subler + * + * Created by Ryan Walklin on 23/09/09. + * Copyright 2009 Test Toast. All rights reserved. + * + */ + +#include +#include +#include +#include +#include +#include + +#include "MatroskaParser.h" +#include "MatroskaFile.h" + +#pragma mark Parser callbacks + +#define CACHESIZE 0xFFFFFFF + +/* StdIoStream methods */ + +/* read count bytes into buffer starting at file position pos + * return the number of bytes read, -1 on error or 0 on EOF + */ +int StdIoRead(StdIoStream *st, uint64_t pos, void *buffer, int count) { + size_t rd; + if (fseeko(st->fp, pos, SEEK_SET) == -1) { + st->error = errno; + return -1; + } + rd = fread(buffer, 1, count, st->fp); + if (rd == 0) { + if (feof(st->fp)) + return 0; + st->error = errno; + return -1; + } + return rd; +} + +/* scan for a signature sig(big-endian) starting at file position pos + * return position of the first byte of signature or -1 if error/not found + */ +longlong StdIoScan(StdIoStream *st, uint64_t start, uint32_t signature) { + uint32_t c; + uint32_t cmp = 0; + FILE *fp = st->fp; + + if (fseeko(fp, start, SEEK_SET)) + return -1; + + while ((c = getc(fp)) != EOF) { + cmp = ((cmp << 8) | c) & 0xffffffff; + if (cmp == signature) + return ftell(fp) - 4; + } + + return -1; +} + +/* return cache size, this is used to limit readahead */ +unsigned StdIoGetCacheSize(StdIoStream *st) { + return CACHESIZE; +} + +/* return last error message */ +const char *StdIoGetLastError(StdIoStream *st) { + return strerror(st->error); +} + +/* memory allocation, this is done via stdlib */ +void *StdIoMalloc(StdIoStream *st, size_t size) { + return malloc(size); +} + +void *StdIoRealloc(StdIoStream *st, void *mem, size_t size) { + return realloc(mem,size); +} + +void StdIoFree(StdIoStream *st, void *mem) { + free(mem); +} + +/* progress report handler for lengthy operations + * returns 0 to abort operation, nonzero to continue + */ +int StdIoProgress(StdIoStream *st, uint64_t cur, uint64_t max) { + return 1; +} + +MatroskaFile *openMatroskaFile(char *filePath, StdIoStream *ioStream) +{ + char err_msg[256]; + + /* fill in I/O object */ + ioStream->base.read = (int(*)(struct InputStream *, ulonglong, void *, int))StdIoRead; + ioStream->base.scan = (longlong(*)(struct InputStream *, ulonglong, unsigned int))StdIoScan; + ioStream->base.getcachesize = (unsigned int (*)(struct InputStream *))StdIoGetCacheSize; + ioStream->base.geterror = (const char *(*)(struct InputStream *))StdIoGetLastError; + ioStream->base.memalloc = (void *(*)(struct InputStream *, size_t))StdIoMalloc; + ioStream->base.memrealloc = (void *(*)(struct InputStream *, void *, size_t))StdIoRealloc; + ioStream->base.memfree = (void(*)(struct InputStream *, void *))StdIoFree; + ioStream->base.progress = (int (*)(struct InputStream *, uint64_t, uint64_t))StdIoProgress; + + /* open source file */ + ioStream->fp = fopen(filePath,"r"); + if (ioStream->fp == NULL) { + fprintf(stderr, "Can't open '%s': %s\n", filePath, strerror(errno)); + return NULL; + } + + /* Disable ram cache */ + //fcntl (ioStream->fp->_file, F_RDAHEAD, 1); + //fcntl (ioStream->fp->_file, F_NOCACHE, 1); + + /* initialize matroska parser */ + MatroskaFile *mf = mkv_Open(&ioStream->base, /* pointer to I/O object */ + err_msg, sizeof(err_msg)); /* error message is returned here */ + + if (mf == NULL) { + fclose(ioStream->fp); + fprintf(stderr, "Can't parse Matroska file: %s\n", err_msg); + return NULL; + } + + return mf; +} + +void closeMatroskaFile(MatroskaFile *matroskaFile, StdIoStream *ioStream) +{ + /* close matroska parser */ + mkv_Close(matroskaFile); + + /* close file */ + if (ioStream) { + fclose(ioStream->fp); + free(ioStream); + } +} diff --git a/MP42/muxer/MatroskaFile.h b/MP42/muxer/MatroskaFile.h new file mode 100644 index 0000000..cd8b4d9 --- /dev/null +++ b/MP42/muxer/MatroskaFile.h @@ -0,0 +1,23 @@ +/* + * MatroskaFile.h + * Subler + * + * Created by Ryan Walklin on 23/09/09. + * Copyright 2009 Test Toast. All rights reserved. + * + */ + +/* first we need to create an I/O object that the parser will use to read the + * source file + */ + +struct StdIoStream { + struct InputStream base; + FILE *fp; + int error; +}; + +typedef struct StdIoStream StdIoStream; + +MatroskaFile *openMatroskaFile(char *filePath, StdIoStream *ioStream); +void closeMatroskaFile(MatroskaFile *matroskaFile, StdIoStream *ioStream); \ No newline at end of file diff --git a/MP42/muxer/MatroskaParser.c b/MP42/muxer/MatroskaParser.c new file mode 100644 index 0000000..69135e8 --- /dev/null +++ b/MP42/muxer/MatroskaParser.c @@ -0,0 +1,3361 @@ +/* + * Copyright (c) 2004-2008 Mike Matsnev. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice immediately at the beginning of the file, without modification, + * this list of conditions, and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Absolutely no warranty of function or purpose is made by the author + * Mike Matsnev. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: MatroskaParser.c,v 1.75 2010/08/14 08:38:41 mike Exp $ + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#ifdef _MSC_VER +// MS names some functions differently +#define alloca _alloca +#define inline __inline +#else /* _MSC_VER */ +// support for building with MinGW on Windows +#include +#endif /* _MSC_VER */ +#include +#endif /* _WIN32 */ + +#ifdef HAVE_ALLOCA_H +#include +#endif + +#ifndef EVCBUG +#define EVCBUG +#endif + +#include "matroskaparser.h" + +#ifdef MATROSKA_COMPRESSION_SUPPORT +#include +#endif + +#define EBML_VERSION 1 +#define EBML_MAX_ID_LENGTH 4 +#define EBML_MAX_SIZE_LENGTH 8 +#define MATROSKA_VERSION 2 +#define MATROSKA_DOCTYPE "matroska" +#define WEBM_DOCTYPE "webm" + +#define MAX_STRING_LEN 1023 +#define QSEGSIZE 512 +#define MAX_TRACKS 32 +#define MAX_READAHEAD (256*1024) + +#define MAXCLUSTER (64*1048576) +#define MAXFRAME (4*1048576) + +#ifdef _MSC_VER +#define LL(x) x##i64 +#define ULL(x) x##ui64 +#else +#define LL(x) x##ll +#define ULL(x) x##ull +#endif + +#define MAXU64 ULL(0xffffffffffffffff) +#define ONE ULL(1) + +// compatibility +static char *mystrdup(struct InputStream *is,const char *src) { + size_t len; + char *dst; + + if (src==NULL) + return NULL; + + len = strlen(src); + dst = is->memalloc(is,len+1); + if (dst==NULL) + return NULL; + + memcpy(dst,src,len+1); + + return dst; +} + +static void mystrlcpy(char *dst,const char *src,unsigned size) { + unsigned i; + + for (i=0;i+1 0) + *dest = '\0'; + return; + } + + while (*fmt && dest < de) + switch (state) { + case 0: + if (*fmt == '%') { + ++fmt; + state = 1; + width = zero = neg = ll = 0; + } else + *dest++ = *fmt++; + break; + case 1: + if (*fmt == '-') { + neg = 1; + ++fmt; + state = 2; + break; + } + if (*fmt == '0') + zero = 1; + state = 2; + case 2: + if (*fmt >= '0' && *fmt <= '9') { + width = width * 10 + *fmt++ - '0'; + break; + } + state = 3; + case 3: + if (*fmt == 'l') { + ++ll; + ++fmt; + break; + } + state = 4; + case 4: + switch (*fmt) { + case 's': + myvsnprintf_string(&dest,de,va_arg(ap,const char *)); + break; + case 'd': + switch (ll) { + case 0: + myvsnprintf_int(&dest,de,width,zero,neg,10,'a',va_arg(ap,int)); + break; + case 1: + myvsnprintf_int(&dest,de,width,zero,neg,10,'a',va_arg(ap,long)); + break; + case 2: + myvsnprintf_int(&dest,de,width,zero,neg,10,'a',va_arg(ap,longlong)); + break; + } + break; + case 'u': + switch (ll) { + case 0: + myvsnprintf_uint(&dest,de,width,zero,neg,10,'a',va_arg(ap,unsigned int)); + break; + case 1: + myvsnprintf_uint(&dest,de,width,zero,neg,10,'a',va_arg(ap,unsigned long)); + break; + case 2: + myvsnprintf_uint(&dest,de,width,zero,neg,10,'a',va_arg(ap,ulonglong)); + break; + } + break; + case 'x': + switch (ll) { + case 0: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'a',va_arg(ap,unsigned int)); + break; + case 1: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'a',va_arg(ap,unsigned long)); + break; + case 2: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'a',va_arg(ap,ulonglong)); + break; + } + break; + case 'X': + switch (ll) { + case 0: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'A',va_arg(ap,unsigned int)); + break; + case 1: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'A',va_arg(ap,unsigned long)); + break; + case 2: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'A',va_arg(ap,ulonglong)); + break; + } + break; + default: + break; + } + ++fmt; + state = 0; + break; + default: + state = 0; + break; + } + *dest = '\0'; +} + +static void errorjmp(MatroskaFile *mf,const char *fmt, ...) { + va_list ap; + + va_start(ap, fmt); + myvsnprintf(mf->errmsg,sizeof(mf->errmsg),fmt,ap); + va_end(ap); + + mf->flags |= MPF_ERROR; + + longjmp(mf->jb,1); +} + +/////////////////////////////////////////////////////////////////////////// +// arrays +static void *ArrayAlloc(MatroskaFile *mf,void **base, + unsigned *cur,unsigned *max,unsigned elem_size) +{ + if (*cur>=*max) { + void *np; + unsigned newsize = *max * 2; + if (newsize==0) + newsize = 1; + + np = mf->cache->memrealloc(mf->cache,*base,newsize*elem_size); + if (np==NULL) + errorjmp(mf,"Out of memory in ArrayAlloc"); + + *base = np; + *max = newsize; + } + + return (char*)*base + elem_size * (*cur)++; +} + +static void ArrayReleaseMemory(MatroskaFile *mf,void **base, + unsigned cur,unsigned *max,unsigned elem_size) +{ + if (cur<*max) { + void *np = mf->cache->memrealloc(mf->cache,*base,cur*elem_size); + *base = np; + *max = cur; + } +} + + +#define ASGET(f,s,name) ArrayAlloc((f),(void**)&(s)->name,&(s)->n##name,&(s)->n##name##Size,sizeof(*((s)->name))) +#define AGET(f,name) ArrayAlloc((f),(void**)&(f)->name,&(f)->n##name,&(f)->n##name##Size,sizeof(*((f)->name))) +#define ARELEASE(f,s,name) ArrayReleaseMemory((f),(void**)&(s)->name,(s)->n##name,&(s)->n##name##Size,sizeof(*((s)->name))) + +/////////////////////////////////////////////////////////////////////////// +// queues +static struct QueueEntry *QPut(struct Queue *q,struct QueueEntry *qe) { + if (q->tail) + q->tail->next = qe; + qe->next = NULL; + q->tail = qe; + if (q->head==NULL) + q->head = qe; + + return qe; +} + +static struct QueueEntry *QGet(struct Queue *q) { + struct QueueEntry *qe = q->head; + if (qe == NULL) + return NULL; + q->head = qe->next; + if (q->tail == qe) + q->tail = NULL; + return qe; +} + +static struct QueueEntry *QAlloc(MatroskaFile *mf) { + struct QueueEntry *qe,**qep; + if (mf->QFreeList == NULL) { + unsigned i; + + qep = AGET(mf,QBlocks); + + *qep = mf->cache->memalloc(mf->cache,QSEGSIZE * sizeof(*qe)); + if (*qep == NULL) + errorjmp(mf,"Ouf of memory"); + + qe = *qep; + + for (i=0;iQFreeList = qe; + } + + qe = mf->QFreeList; + mf->QFreeList = qe->next; + + return qe; +} + +static inline void QFree(MatroskaFile *mf,struct QueueEntry *qe) { + qe->next = mf->QFreeList; + mf->QFreeList = qe; +} + +// fill the buffer at current position +static void fillbuf(MatroskaFile *mf) { + int rd; + + // advance buffer pointers + mf->bufbase += mf->buflen; + mf->buflen = mf->bufpos = 0; + + // get the relevant page + rd = mf->cache->read(mf->cache, mf->bufbase, mf->inbuf, IBSZ); + if (rd<0) + errorjmp(mf,"I/O Error: %s",mf->cache->geterror(mf->cache)); + + mf->buflen = rd; +} + +// fill the buffer and return next char +static int nextbuf(MatroskaFile *mf) { + fillbuf(mf); + + if (mf->bufpos < mf->buflen) + return (unsigned char)(mf->inbuf[mf->bufpos++]); + + return EOF; +} + +static inline int readch(MatroskaFile *mf) { + return mf->bufpos < mf->buflen ? (unsigned char)(mf->inbuf[mf->bufpos++]) : nextbuf(mf); +} + +static inline ulonglong filepos(MatroskaFile *mf) { + return mf->bufbase + mf->bufpos; +} + +static void readbytes(MatroskaFile *mf,void *buffer,int len) { + char *cp = buffer; + int nb = mf->buflen - mf->bufpos; + + if (nb > len) + nb = len; + + memcpy(cp, mf->inbuf + mf->bufpos, nb); + mf->bufpos += nb; + len -= nb; + cp += nb; + + if (len>0) { + mf->bufbase += mf->buflen; + mf->bufpos = mf->buflen = 0; + + nb = mf->cache->read(mf->cache, mf->bufbase, cp, len); + if (nb<0) + errorjmp(mf,"I/O Error: %s",mf->cache->geterror(mf->cache)); + if (nb != len) + errorjmp(mf,"Short read: got %d bytes of %d",nb,len); + mf->bufbase += len; + } +} + +static void skipbytes(MatroskaFile *mf,ulonglong len) { + int nb = mf->buflen - mf->bufpos; + + if (nb > len) + nb = (int)len; + + mf->bufpos += nb; + len -= nb; + + if (len>0) { + mf->bufbase += mf->buflen; + mf->bufpos = mf->buflen = 0; + + mf->bufbase += len; + } +} + +static void seek(MatroskaFile *mf,ulonglong pos) { + // see if pos is inside buffer + if (pos>=mf->bufbase && posbufbase+mf->buflen) + mf->bufpos = (unsigned)(pos - mf->bufbase); + else { + // invalidate buffer and set pointer + mf->bufbase = pos; + mf->buflen = mf->bufpos = 0; + } +} + +/////////////////////////////////////////////////////////////////////////// +// floating point +static inline MKFLOAT mkfi(int i) { +#ifdef MATROSKA_INTEGER_ONLY + MKFLOAT f; + f.v = (longlong)i << 32; + return f; +#else + return i; +#endif +} + +static inline longlong mul3(MKFLOAT scale,longlong tc) { +#ifdef MATROSKA_INTEGER_ONLY + // x1 x0 + // y1 y0 + // -------------- + // x0*y0 + // x1*y0 + // x0*y1 + // x1*y1 + // -------------- + // .. r1 r0 .. + // + // r = ((x0*y0) >> 32) + (x1*y0) + (x0*y1) + ((x1*y1) << 32) + unsigned x0,x1,y0,y1; + ulonglong p; + char sign = 0; + + if (scale.v < 0) + sign = !sign, scale.v = -scale.v; + if (tc < 0) + sign = !sign, tc = -tc; + + x0 = (unsigned)scale.v; + x1 = (unsigned)((ulonglong)scale.v >> 32); + y0 = (unsigned)tc; + y1 = (unsigned)((ulonglong)tc >> 32); + + p = (ulonglong)x0*y0 >> 32; + p += (ulonglong)x0*y1; + p += (ulonglong)x1*y0; + p += (ulonglong)(x1*y1) << 32; + + return p; +#else + return (longlong)(scale * tc); +#endif +} + +/////////////////////////////////////////////////////////////////////////// +// EBML support +static int readID(MatroskaFile *mf) { + int c1,c2,c3,c4; + + c1 = readch(mf); + if (c1 == EOF) + return EOF; + + if (c1 & 0x80) + return c1; + + if ((c1 & 0xf0) == 0) + errorjmp(mf,"Invalid first byte of EBML ID: %02X",c1); + + c2 = readch(mf); + if (c2 == EOF) +fail: + errorjmp(mf,"Got EOF while reading EBML ID"); + + if ((c1 & 0xc0) == 0x40) + return (c1<<8) | c2; + + c3 = readch(mf); + if (c3 == EOF) + goto fail; + + if ((c1 & 0xe0) == 0x20) + return (c1<<16) | (c2<<8) | c3; + + c4 = readch(mf); + if (c4 == EOF) + goto fail; + + if ((c1 & 0xf0) == 0x10) + return (c1<<24) | (c2<<16) | (c3<<8) | c4; + + return 0; // NOT REACHED +} + +static ulonglong readVLUIntImp(MatroskaFile *mf,int *mask) { + int c,d,m; + ulonglong v = 0; + + c = readch(mf); + if (c == EOF) + return 0; // XXX should errorjmp()? + + if (c == 0) + errorjmp(mf,"Invalid first byte of EBML integer: 0"); + + for (m=0;;++m) { + if (c & (0x80 >> m)) { + c &= 0x7f >> m; + if (mask) + *mask = m; + return v | ((ulonglong)c << m*8); + } + d = readch(mf); + if (d == EOF) + errorjmp(mf,"Got EOF while reading EBML unsigned integer"); + v = (v<<8) | d; + } + // NOT REACHED +} + +static inline ulonglong readVLUInt(MatroskaFile *mf) { + return readVLUIntImp(mf,NULL); +} + +static ulonglong readSizeUnspec(MatroskaFile *mf) { + int m; + ulonglong v = readVLUIntImp(mf,&m); + + // see if it's unspecified + if (v == (MAXU64 >> (57-m*7))) + return MAXU64; + + return v; +} + +static ulonglong readSize(MatroskaFile *mf) { + ulonglong v = readSizeUnspec(mf); + + // see if it's unspecified + if (v == MAXU64) + errorjmp(mf,"Unspecified element size is not supported here."); + + return v; +} + +static inline longlong readVLSInt(MatroskaFile *mf) { + static longlong bias[8] = { (ONE<<6)-1, (ONE<<13)-1, (ONE<<20)-1, (ONE<<27)-1, + (ONE<<34)-1, (ONE<<41)-1, (ONE<<48)-1, (ONE<<55)-1 }; + + int m; + longlong v = readVLUIntImp(mf,&m); + + return v - bias[m]; +} + +static ulonglong readUInt(MatroskaFile *mf,unsigned int len) { + int c; + unsigned int m = len; + ulonglong v = 0; + + if (len==0) + return v; + if (len>8) + errorjmp(mf,"Unsupported integer size in readUInt: %u",len); + + do { + c = readch(mf); + if (c == EOF) + errorjmp(mf,"Got EOF while reading EBML unsigned integer"); + v = (v<<8) | c; + } while (--m); + + return v; +} + +static inline longlong readSInt(MatroskaFile *mf,unsigned int len) { + longlong v = readUInt(mf,(unsigned)len); + int s = 64 - (len<<3); + return (v << s) >> s; +} + +static MKFLOAT readFloat(MatroskaFile *mf,unsigned int len) { +#ifdef MATROSKA_INTEGER_ONLY + MKFLOAT f; + int shift; +#else + union { + unsigned int ui; + ulonglong ull; + float f; + double d; + } u; +#endif + + if (len!=4 && len!=8) + errorjmp(mf,"Invalid float size in readFloat: %u",len); + +#ifdef MATROSKA_INTEGER_ONLY + if (len == 4) { + unsigned ui = (unsigned)readUInt(mf,(unsigned)len); + f.v = (ui & 0x7fffff) | 0x800000; + if (ui & 0x80000000) + f.v = -f.v; + shift = (ui >> 23) & 0xff; + if (shift == 0) // assume 0 +zero: + shift = 0, f.v = 0; + else if (shift == 255) +inf: + if (ui & 0x80000000) + f.v = LL(0x8000000000000000); + else + f.v = LL(0x7fffffffffffffff); + else { + shift += -127 + 9; + if (shift > 39) + goto inf; +shift: + if (shift < 0) + f.v = f.v >> -shift; + else if (shift > 0) + f.v = f.v << shift; + } + } else if (len == 8) { + ulonglong ui = readUInt(mf,(unsigned)len); + f.v = (ui & LL(0xfffffffffffff)) | LL(0x10000000000000); + if (ui & 0x80000000) + f.v = -f.v; + shift = (int)((ui >> 52) & 0x7ff); + if (shift == 0) // assume 0 + goto zero; + else if (shift == 2047) + goto inf; + else { + shift += -1023 - 20; + if (shift > 10) + goto inf; + goto shift; + } + } + + return f; +#else + if (len==4) { + u.ui = (unsigned int)readUInt(mf,(unsigned)len); + return u.f; + } + + if (len==8) { + u.ull = readUInt(mf,(unsigned)len); + return u.d; + } + + return 0; +#endif +} + +static void readString(MatroskaFile *mf,ulonglong len,char *buffer,int buflen) { + int nread; + + if (buflen<1) + errorjmp(mf,"Invalid buffer size in readString: %d",buflen); + + nread = buflen - 1; + + if (nread > len) + nread = (int)len; + + readbytes(mf,buffer,nread); + len -= nread; + + if (len>0) + skipbytes(mf,len); + + buffer[nread] = '\0'; +} + +static void readLangCC(MatroskaFile *mf, ulonglong len, char lcc[4]) { + unsigned todo = len > 3 ? 3 : (int)len; + + lcc[0] = lcc[1] = lcc[2] = lcc[3] = 0; + readbytes(mf, lcc, todo); + skipbytes(mf, len - todo); +} + +/////////////////////////////////////////////////////////////////////////// +// file parser +#define FOREACH2(f,tl,clid) \ + { \ + ulonglong tmplen = (tl); \ + { \ + ulonglong start = filepos(f); \ + ulonglong cur,len; \ + int id; \ + for (;;) { \ + cur = filepos(mf); \ + if (tmplen != MAXU64 && cur == start + tmplen) \ + break; \ + id = readID(f); \ + if (id==EOF) \ + errorjmp(mf,"Unexpected EOF while reading EBML container"); \ + len = id == clid ? readSizeUnspec(mf) : readSize(mf); \ + switch (id) { + +#define FOREACH(f,tl) FOREACH2(f,tl,EOF) + +#define RESTART() (tmplen=len),(start=cur) + +#define ENDFOR1(f) \ + default: \ + skipbytes(f,len); \ + break; \ + } +#define ENDFOR2() \ + } \ + } \ + } + +#define ENDFOR(f) ENDFOR1(f) ENDFOR2() + +#define myalloca(f,c) alloca(c) +#define STRGETF(f,v,len,func) \ + { \ + char *TmpVal; \ + unsigned TmpLen = (len)>MAX_STRING_LEN ? MAX_STRING_LEN : (unsigned)(len); \ + TmpVal = func(f->cache,TmpLen+1); \ + if (TmpVal == NULL) \ + errorjmp(mf,"Out of memory"); \ + readString(f,len,TmpVal,TmpLen+1); \ + (v) = TmpVal; \ + } + +#define STRGETA(f,v,len) STRGETF(f,v,len,myalloca) +#define STRGETM(f,v,len) STRGETF(f,v,len,f->cache->memalloc) + +static void parseEBML(MatroskaFile *mf,ulonglong toplen) { + ulonglong v; + char buf[32]; + + FOREACH(mf,toplen) + case 0x4286: // Version + v = readUInt(mf,(unsigned)len); + break; + case 0x42f7: // ReadVersion + v = readUInt(mf,(unsigned)len); + if (v > EBML_VERSION) + errorjmp(mf,"File requires version %d EBML parser",(int)v); + break; + case 0x42f2: // MaxIDLength + v = readUInt(mf,(unsigned)len); + if (v > EBML_MAX_ID_LENGTH) + errorjmp(mf,"File has identifiers longer than %d",(int)v); + break; + case 0x42f3: // MaxSizeLength + v = readUInt(mf,(unsigned)len); + if (v > EBML_MAX_SIZE_LENGTH) + errorjmp(mf,"File has integers longer than %d",(int)v); + break; + case 0x4282: // DocType + readString(mf,len,buf,sizeof(buf)); + if (strcmp(buf,MATROSKA_DOCTYPE) != 0 && strcmp(buf,WEBM_DOCTYPE) != 0) + errorjmp(mf,"Unsupported DocType: %s",buf); + break; + case 0x4287: // DocTypeVersion + v = readUInt(mf,(unsigned)len); + break; + case 0x4285: // DocTypeReadVersion + v = readUInt(mf,(unsigned)len); + if (v > MATROSKA_VERSION) + errorjmp(mf,"File requires version %d Matroska parser",(int)v); + break; + ENDFOR(mf); +} + +static void parseSeekEntry(MatroskaFile *mf,ulonglong toplen) { + int seekid = 0; + ulonglong pos = (ulonglong)-1; + + FOREACH(mf,toplen) + case 0x53ab: // SeekID + if (len>EBML_MAX_ID_LENGTH) + errorjmp(mf,"Invalid ID size in parseSeekEntry: %d\n",(int)len); + seekid = (int)readUInt(mf,(unsigned)len); + break; + case 0x53ac: // SeekPos + pos = readUInt(mf,(unsigned)len); + break; + ENDFOR(mf); + + if (pos == (ulonglong)-1) + errorjmp(mf,"Invalid element position in parseSeekEntry"); + + pos += mf->pSegment; + switch (seekid) { + case 0x114d9b74: // next SeekHead + if (mf->pSeekHead) + errorjmp(mf,"SeekHead contains more than one SeekHead pointer"); + mf->pSeekHead = pos; + break; + case 0x1549a966: // SegmentInfo + mf->pSegmentInfo = pos; + break; + case 0x1f43b675: // Cluster + if (!mf->pCluster) + mf->pCluster = pos; + break; + case 0x1654ae6b: // Tracks + mf->pTracks = pos; + break; + case 0x1c53bb6b: // Cues + mf->pCues = pos; + break; + case 0x1941a469: // Attachments + mf->pAttachments = pos; + break; + case 0x1043a770: // Chapters + mf->pChapters = pos; + break; + case 0x1254c367: // tags + mf->pTags = pos; + break; + } +} + +static void parseSeekHead(MatroskaFile *mf,ulonglong toplen) { + FOREACH(mf,toplen) + case 0x4dbb: + parseSeekEntry(mf,len); + break; + ENDFOR(mf); +} + +static void parseSegmentInfo(MatroskaFile *mf,ulonglong toplen) { + MKFLOAT duration = mkfi(0); + + if (mf->seen.SegmentInfo) { + skipbytes(mf,toplen); + return; + } + + mf->seen.SegmentInfo = 1; + mf->Seg.TimecodeScale = 1000000; // Default value + + FOREACH(mf,toplen) + case 0x73a4: // SegmentUID + if (len!=sizeof(mf->Seg.UID)) + errorjmp(mf,"SegmentUID size is not %d bytes",mf->Seg.UID); + readbytes(mf,mf->Seg.UID,sizeof(mf->Seg.UID)); + break; + case 0x7384: // SegmentFilename + STRGETM(mf,mf->Seg.Filename,len); + break; + case 0x3cb923: // PrevUID + if (len!=sizeof(mf->Seg.PrevUID)) + errorjmp(mf,"PrevUID size is not %d bytes",mf->Seg.PrevUID); + readbytes(mf,mf->Seg.PrevUID,sizeof(mf->Seg.PrevUID)); + break; + case 0x3c83ab: // PrevFilename + STRGETM(mf,mf->Seg.PrevFilename,len); + break; + case 0x3eb923: // NextUID + if (len!=sizeof(mf->Seg.NextUID)) + errorjmp(mf,"NextUID size is not %d bytes",mf->Seg.NextUID); + readbytes(mf,mf->Seg.NextUID,sizeof(mf->Seg.NextUID)); + break; + case 0x3e83bb: // NextFilename + STRGETM(mf,mf->Seg.NextFilename,len); + break; + case 0x2ad7b1: // TimecodeScale + mf->Seg.TimecodeScale = readUInt(mf,(unsigned)len); + if (mf->Seg.TimecodeScale == 0) + errorjmp(mf,"Segment timecode scale is zero"); + break; + case 0x4489: // Duration + duration = readFloat(mf,(unsigned)len); + break; + case 0x4461: // DateUTC + mf->Seg.DateUTC = readUInt(mf,(unsigned)len); + mf->Seg.DateUTCValid = 1; + break; + case 0x7ba9: // Title + STRGETM(mf,mf->Seg.Title,len); + break; + case 0x4d80: // MuxingApp + STRGETM(mf,mf->Seg.MuxingApp,len); + break; + case 0x5741: // WritingApp + STRGETM(mf,mf->Seg.WritingApp,len); + break; + ENDFOR(mf); + + mf->Seg.Duration = mul3(duration,mf->Seg.TimecodeScale); +} + +static void parseFirstCluster(MatroskaFile *mf,ulonglong toplen) { + int seenTimecode = 0, seenBlock = 0; + longlong tc; + ulonglong clstart = filepos(mf); + + mf->seen.Cluster = 1; + mf->firstTimecode = 0; + + FOREACH2(mf,toplen,0x1f43b675) + case 0xe7: // Timecode + tc = readUInt(mf,(unsigned)len); + if (!seenTimecode) { + seenTimecode = 1; + mf->firstTimecode += tc; + } + + if (seenBlock) { +out: + if (toplen != MAXU64) + skipbytes(mf,clstart + toplen - filepos(mf)); + else if (len != MAXU64) + skipbytes(mf,cur + len - filepos(mf)); + return; + } + break; + case 0xa3: // BlockEx + readVLUInt(mf); // track number + tc = readSInt(mf, 2); + if (!seenBlock) { + seenBlock = 1; + mf->firstTimecode += tc; + } + + if (seenTimecode) + goto out; + break; + case 0xa0: // BlockGroup + FOREACH(mf,len) + case 0xa1: // Block + readVLUInt(mf); // track number + tc = readSInt(mf,2); + if (!seenBlock) { + seenBlock = 1; + mf->firstTimecode += tc; + } + + if (seenTimecode) + goto out; + ENDFOR(mf); + break; + case 0x1f43b675: + return; + ENDFOR(mf); +} + +static void parseVideoInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *ti) { + ulonglong v; + char dW = 0, dH = 0; + + FOREACH(mf,toplen) + case 0x9a: // FlagInterlaced + ti->AV.Video.Interlaced = readUInt(mf,(unsigned)len)!=0; + break; + case 0x53b8: // StereoMode + v = readUInt(mf,(unsigned)len); + if (v>3) + errorjmp(mf,"Invalid stereo mode"); + ti->AV.Video.StereoMode = (unsigned char)v; + break; + case 0xb0: // PixelWidth + v = readUInt(mf,(unsigned)len); + if (v>0xffffffff) + errorjmp(mf,"PixelWidth is too large"); + ti->AV.Video.PixelWidth = (unsigned)v; + if (!dW) + ti->AV.Video.DisplayWidth = ti->AV.Video.PixelWidth; + break; + case 0xba: // PixelHeight + v = readUInt(mf,(unsigned)len); + if (v>0xffffffff) + errorjmp(mf,"PixelHeight is too large"); + ti->AV.Video.PixelHeight = (unsigned)v; + if (!dH) + ti->AV.Video.DisplayHeight = ti->AV.Video.PixelHeight; + break; + case 0x54b0: // DisplayWidth + v = readUInt(mf,(unsigned)len); + if (v>0xffffffff) + errorjmp(mf,"DisplayWidth is too large"); + ti->AV.Video.DisplayWidth = (unsigned)v; + dW = 1; + break; + case 0x54ba: // DisplayHeight + v = readUInt(mf,(unsigned)len); + if (v>0xffffffff) + errorjmp(mf,"DisplayHeight is too large"); + ti->AV.Video.DisplayHeight = (unsigned)v; + dH = 1; + break; + case 0x54b2: // DisplayUnit + v = readUInt(mf,(unsigned)len); + ti->AV.Video.DisplayUnit = (unsigned char)v; + break; + case 0x54b3: // AspectRatioType + v = readUInt(mf,(unsigned)len); + ti->AV.Video.AspectRatioType = (unsigned char)v; + break; + case 0x54aa: // PixelCropBottom + v = readUInt(mf,(unsigned)len); + if (v>0xffffffff) + errorjmp(mf,"PixelCropBottom is too large"); + ti->AV.Video.CropB = (unsigned)v; + break; + case 0x54bb: // PixelCropTop + v = readUInt(mf,(unsigned)len); + if (v>0xffffffff) + errorjmp(mf,"PixelCropTop is too large"); + ti->AV.Video.CropT = (unsigned)v; + break; + case 0x54cc: // PixelCropLeft + v = readUInt(mf,(unsigned)len); + if (v>0xffffffff) + errorjmp(mf,"PixelCropLeft is too large"); + ti->AV.Video.CropL = (unsigned)v; + break; + case 0x54dd: // PixelCropRight + v = readUInt(mf,(unsigned)len); + if (v>0xffffffff) + errorjmp(mf,"PixelCropRight is too large"); + ti->AV.Video.CropR = (unsigned)v; + break; + case 0x2eb524: // ColourSpace + ti->AV.Video.ColourSpace = (unsigned)readUInt(mf,4); + break; + case 0x2fb523: // GammaValue + ti->AV.Video.GammaValue = readFloat(mf,(unsigned)len); + break; + ENDFOR(mf); +} + +static void parseAudioInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *ti) { + ulonglong v; + + FOREACH(mf,toplen) + case 0xb5: // SamplingFrequency + ti->AV.Audio.SamplingFreq = readFloat(mf,(unsigned)len); + break; + case 0x78b5: // OutputSamplingFrequency + ti->AV.Audio.OutputSamplingFreq = readFloat(mf,(unsigned)len); + break; + case 0x9f: // Channels + v = readUInt(mf,(unsigned)len); + if (v<1 || v>255) + errorjmp(mf,"Invalid Channels value"); + ti->AV.Audio.Channels = (unsigned char)v; + break; + case 0x7d7b: // ChannelPositions + skipbytes(mf,len); + break; + case 0x6264: // BitDepth + v = readUInt(mf,(unsigned)len); +#if 0 + if ((v<1 || v>255) && !IsWritingApp(mf,"AVI-Mux GUI")) + errorjmp(mf,"Invalid BitDepth: %d",(int)v); +#endif + ti->AV.Audio.BitDepth = (unsigned char)v; + break; + ENDFOR(mf); + + if (ti->AV.Audio.Channels == 0) + ti->AV.Audio.Channels = 1; + if (mkv_TruncFloat(ti->AV.Audio.SamplingFreq) == 0) + ti->AV.Audio.SamplingFreq = mkfi(8000); + if (mkv_TruncFloat(ti->AV.Audio.OutputSamplingFreq)==0) + ti->AV.Audio.OutputSamplingFreq = ti->AV.Audio.SamplingFreq; +} + +static void CopyStr(char **src,char **dst) { + size_t l; + + if (!*src) + return; + + l = strlen(*src)+1; + memcpy(*dst,*src,l); + *src = *dst; + *dst += l; +} + +static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { + struct TrackInfo t,*tp,**tpp; + ulonglong v; + char *cp = NULL, *cs = NULL; + size_t cplen = 0, cslen = 0, cpadd = 0; + unsigned CompScope, num_comp = 0; + + if (mf->nTracks >= MAX_TRACKS) + errorjmp(mf,"Too many tracks."); + + // clear track info + memset(&t,0,sizeof(t)); + + // fill default values + t.Enabled = 1; + t.Default = 1; + t.Lacing = 1; + t.TimecodeScale = mkfi(1); + t.DecodeAll = 1; + + FOREACH(mf,toplen) + case 0xd7: // TrackNumber + v = readUInt(mf,(unsigned)len); + if (v>255) + errorjmp(mf,"Track number is >255 (%d)",(int)v); + t.Number = (unsigned char)v; + break; + case 0x73c5: // TrackUID + t.UID = readUInt(mf,(unsigned)len); + break; + case 0x83: // TrackType + v = readUInt(mf,(unsigned)len); + if (v<1 || v>254) + errorjmp(mf,"Invalid track type: %d",(int)v); + t.Type = (unsigned char)v; + break; + case 0xb9: // Enabled + t.Enabled = readUInt(mf,(unsigned)len)!=0; + break; + case 0x88: // Default + t.Default = readUInt(mf,(unsigned)len)!=0; + break; + case 0x9c: // Lacing + t.Lacing = readUInt(mf,(unsigned)len)!=0; + break; + case 0x6de7: // MinCache + v = readUInt(mf,(unsigned)len); + if (v > 0xffffffff) + errorjmp(mf,"MinCache is too large"); + t.MinCache = (unsigned)v; + break; + case 0x6df8: // MaxCache + v = readUInt(mf,(unsigned)len); + if (v > 0xffffffff) + errorjmp(mf,"MaxCache is too large"); + t.MaxCache = (unsigned)v; + break; + case 0x23e383: // DefaultDuration + t.DefaultDuration = readUInt(mf,(unsigned)len); + break; + case 0x23314f: // TrackTimecodeScale + t.TimecodeScale = readFloat(mf,(unsigned)len); + break; + case 0x55ee: // MaxBlockAdditionID + t.MaxBlockAdditionID = (unsigned)readUInt(mf,(unsigned)len); + break; + case 0x536e: // Name + if (t.Name) + errorjmp(mf,"Duplicate Track Name"); + STRGETA(mf,t.Name,len); + break; + case 0x22b59c: // Language + readLangCC(mf, len, t.Language); + break; + case 0x86: // CodecID + if (t.CodecID) + errorjmp(mf,"Duplicate CodecID"); + STRGETA(mf,t.CodecID,len); + break; + case 0x63a2: // CodecPrivate + if (cp) + errorjmp(mf,"Duplicate CodecPrivate"); + if (len>2097152) // 2MB + errorjmp(mf,"CodecPrivate is too large: %d",(int)len); + cplen = (unsigned)len; + cp = alloca(cplen); + readbytes(mf,cp,(int)cplen); + break; + case 0x258688: // CodecName + skipbytes(mf,len); + break; + case 0x3a9697: // CodecSettings + skipbytes(mf,len); + break; + case 0x3b4040: // CodecInfoURL + skipbytes(mf,len); + break; + case 0x26b240: // CodecDownloadURL + skipbytes(mf,len); + break; + case 0xaa: // CodecDecodeAll + t.DecodeAll = readUInt(mf,(unsigned)len)!=0; + break; + case 0x6fab: // TrackOverlay + v = readUInt(mf,(unsigned)len); + if (v>255) + errorjmp(mf,"Track number in TrackOverlay is too large: %d",(int)v); + t.TrackOverlay = (unsigned char)v; + break; + case 0xe0: // VideoInfo + parseVideoInfo(mf,len,&t); + break; + case 0xe1: // AudioInfo + parseAudioInfo(mf,len,&t); + break; + case 0x6d80: // ContentEncodings + FOREACH(mf,len) + case 0x6240: // ContentEncoding + // fill in defaults + t.CompEnabled = 1; + t.CompMethod = COMP_ZLIB; + CompScope = 1; + if (++num_comp > 1) + return; // only one compression layer supported + FOREACH(mf,len) + case 0x5031: // ContentEncodingOrder + readUInt(mf,(unsigned)len); + break; + case 0x5032: // ContentEncodingScope + CompScope = (unsigned)readUInt(mf,(unsigned)len); + break; + case 0x5033: // ContentEncodingType + if (readUInt(mf,(unsigned)len) != 0) + return; // encryption is not supported + break; + case 0x5034: // ContentCompression + FOREACH(mf,len) + case 0x4254: // ContentCompAlgo + v = readUInt(mf,(unsigned)len); + t.CompEnabled = 1; + switch (v) { + case 0: // Zlib + t.CompMethod = COMP_ZLIB; + break; + case 1: // BZlib + t.CompMethod = COMP_BZIP; + break; + case 3: // prepend fixed data + t.CompMethod = COMP_PREPEND; + break; + default: + return; // unsupported compression, skip track + } + break; + case 0x4255: // ContentCompSettings + if (len > 256) + return; + cslen = (unsigned)len; + cs = alloca(cslen); + readbytes(mf, cs, (int)cslen); + break; + ENDFOR(mf); + break; + // TODO Implement Encryption/Signatures + ENDFOR(mf); + break; + ENDFOR(mf); + break; + ENDFOR(mf); + + // validate track info + if (!t.CodecID) + errorjmp(mf,"Track has no Codec ID"); + + if (t.UID != 0) { + unsigned i; + for (i = 0; i < mf->nTracks; ++i) + if (mf->Tracks[i]->UID == t.UID) // duplicate track entry + return; + } + +#ifdef MATROSKA_COMPRESSION_SUPPORT + // handle compressed CodecPrivate + if (t.CompEnabled && t.CompMethod == COMP_ZLIB && (CompScope & 2) && cplen > 0) { + z_stream zs; + Bytef tmp[64], *ncp; + int code; + uLong ncplen; + + memset(&zs,0,sizeof(zs)); + if (inflateInit(&zs) != Z_OK) + errorjmp(mf, "inflateInit failed"); + + zs.next_in = (Bytef *)cp; + zs.avail_in = (uInt)cplen; + + do { + zs.next_out = tmp; + zs.avail_out = sizeof(tmp); + + code = inflate(&zs, Z_NO_FLUSH); + } while (code == Z_OK); + + if (code != Z_STREAM_END) + errorjmp(mf, "invalid compressed data in CodecPrivate"); + + ncplen = zs.total_out; + ncp = alloca(ncplen); + + inflateReset(&zs); + + zs.next_in = (Bytef *)cp; + zs.avail_in = (uInt)cplen; + zs.next_out = ncp; + zs.avail_out = ncplen; + + if (inflate(&zs, Z_FINISH) != Z_STREAM_END) + errorjmp(mf, "inflate failed"); + + inflateEnd(&zs); + + cp = (char *)ncp; + cplen = ncplen; + } +#endif + + if (t.CompEnabled && !(CompScope & 1)) { + t.CompEnabled = 0; + cslen = 0; + } + + // allocate new track + tpp = AGET(mf,Tracks); + + // copy strings + if (t.Name) + cpadd += strlen(t.Name)+1; + if (t.CodecID) + cpadd += strlen(t.CodecID)+1; + + tp = mf->cache->memalloc(mf->cache,sizeof(*tp) + cplen + cslen + cpadd); + if (tp == NULL) + errorjmp(mf,"Out of memory"); + + memcpy(tp,&t,sizeof(*tp)); + if (cplen) { + tp->CodecPrivate = tp+1; + tp->CodecPrivateSize = (unsigned)cplen; + memcpy(tp->CodecPrivate,cp,cplen); + } + if (cslen) { + tp->CompMethodPrivate = (char *)(tp+1) + cplen; + tp->CompMethodPrivateSize = (unsigned)cslen; + memcpy(tp->CompMethodPrivate, cs, cslen); + } + + cp = (char*)(tp+1) + cplen + cslen; + CopyStr(&tp->Name,&cp); + CopyStr(&tp->CodecID,&cp); + + // set default language + if (!tp->Language[0]) + memcpy(tp->Language, "eng", 4); + + *tpp = tp; +} + +static void parseTracks(MatroskaFile *mf,ulonglong toplen) { + mf->seen.Tracks = 1; + FOREACH(mf,toplen) + case 0xae: // TrackEntry + parseTrackEntry(mf,len); + break; + ENDFOR(mf); +} + +static void addCue(MatroskaFile *mf,ulonglong pos,ulonglong timecode) { + struct Cue *cc = AGET(mf,Cues); + cc->Time = timecode; + cc->Position = pos; + cc->Track = 0; + cc->Block = 0; +} + +static void fixupCues(MatroskaFile *mf) { + // adjust cues, shift cues if file does not start at 0 + unsigned i; + longlong adjust = mf->firstTimecode * mf->Seg.TimecodeScale; + + for (i=0;inCues;++i) { + mf->Cues[i].Time *= mf->Seg.TimecodeScale; + mf->Cues[i].Time -= adjust; + } +} + +static void parseCues(MatroskaFile *mf,ulonglong toplen) { + jmp_buf jb; + ulonglong v; + struct Cue cc; + unsigned i,j,k; + + mf->seen.Cues = 1; + mf->nCues = 0; + cc.Block = 0; + + memcpy(&jb,&mf->jb,sizeof(jb)); + + if (setjmp(mf->jb)) { + memcpy(&mf->jb,&jb,sizeof(jb)); + mf->nCues = 0; + mf->seen.Cues = 0; + return; + } + + FOREACH(mf,toplen) + case 0xbb: // CuePoint + FOREACH(mf,len) + case 0xb3: // CueTime + cc.Time = readUInt(mf,(unsigned)len); + break; + case 0xb7: // CueTrackPositions + FOREACH(mf,len) + case 0xf7: // CueTrack + v = readUInt(mf,(unsigned)len); + if (v>255) + errorjmp(mf,"CueTrack points to an invalid track: %d",(int)v); + cc.Track = (unsigned char)v; + break; + case 0xf1: // CueClusterPosition + cc.Position = readUInt(mf,(unsigned)len); + break; + case 0x5378: // CueBlockNumber + cc.Block = readUInt(mf,(unsigned)len); + break; + case 0xea: // CodecState + readUInt(mf,(unsigned)len); + break; + case 0xdb: // CueReference + FOREACH(mf,len) + case 0x96: // CueRefTime + readUInt(mf,(unsigned)len); + break; + case 0x97: // CueRefCluster + readUInt(mf,(unsigned)len); + break; + case 0x535f: // CueRefNumber + readUInt(mf,(unsigned)len); + break; + case 0xeb: // CueRefCodecState + readUInt(mf,(unsigned)len); + break; + ENDFOR(mf); + break; + ENDFOR(mf); + break; + ENDFOR(mf); + + if (mf->nCues == 0 && mf->pCluster - mf->pSegment != cc.Position) + addCue(mf,mf->pCluster - mf->pSegment,mf->firstTimecode); + + memcpy(AGET(mf,Cues),&cc,sizeof(cc)); + break; + ENDFOR(mf); + + memcpy(&mf->jb,&jb,sizeof(jb)); + + ARELEASE(mf,mf,Cues); + + // bubble sort the cues and fuck the losers that write unordered cues + if (mf->nCues > 0) + for (i = mf->nCues - 1, k = 1; i > 0 && k > 0; --i) + for (j = k = 0; j < i; ++j) + if (mf->Cues[j].Time > mf->Cues[j+1].Time) { + struct Cue tmp = mf->Cues[j+1]; + mf->Cues[j+1] = mf->Cues[j]; + mf->Cues[j] = tmp; + ++k; + } +} + +static void parseAttachment(MatroskaFile *mf,ulonglong toplen) { + struct Attachment a,*pa; + + memset(&a,0,sizeof(a)); + FOREACH(mf,toplen) + case 0x467e: // Description + STRGETA(mf,a.Description,len); + break; + case 0x466e: // Name + STRGETA(mf,a.Name,len); + break; + case 0x4660: // MimeType + STRGETA(mf,a.MimeType,len); + break; + case 0x46ae: // UID + a.UID = readUInt(mf,(unsigned)len); + break; + case 0x465c: // Data + a.Position = filepos(mf); + a.Length = len; + skipbytes(mf,len); + break; + ENDFOR(mf); + + if (!a.Position) + return; + + pa = AGET(mf,Attachments); + memcpy(pa,&a,sizeof(a)); + + if (a.Description) + pa->Description = mystrdup(mf->cache,a.Description); + if (a.Name) + pa->Name = mystrdup(mf->cache,a.Name); + if (a.MimeType) + pa->MimeType = mystrdup(mf->cache,a.MimeType); +} + +static void parseAttachments(MatroskaFile *mf,ulonglong toplen) { + mf->seen.Attachments = 1; + + FOREACH(mf,toplen) + case 0x61a7: // AttachedFile + parseAttachment(mf,len); + break; + ENDFOR(mf); +} + +static void parseChapter(MatroskaFile *mf,ulonglong toplen,struct Chapter *parent) { + struct ChapterDisplay *disp; + struct ChapterProcess *proc; + struct ChapterCommand *cmd; + struct Chapter *ch = ASGET(mf,parent,Children); + + memset(ch,0,sizeof(*ch)); + + ch->Enabled = 1; + + FOREACH(mf,toplen) + case 0x73c4: // ChapterUID + ch->UID = readUInt(mf,(unsigned)len); + break; + case 0x6e67: // ChapterSegmentUID + if (len != sizeof(ch->SegmentUID)) + skipbytes(mf, len); + else + readbytes(mf, ch->SegmentUID, sizeof(ch->SegmentUID)); + break; + case 0x91: // ChapterTimeStart + ch->Start = readUInt(mf,(unsigned)len); + break; + case 0x92: // ChapterTimeEnd + ch->End = readUInt(mf,(unsigned)len); + break; + case 0x98: // ChapterFlagHidden + ch->Hidden = readUInt(mf,(unsigned)len)!=0; + break; + case 0x4598: // ChapterFlagEnabled + ch->Enabled = readUInt(mf,(unsigned)len)!=0; + break; + case 0x8f: // ChapterTrack + FOREACH(mf,len) + case 0x89: // ChapterTrackNumber + *(ulonglong*)(ASGET(mf,ch,Tracks)) = readUInt(mf,(unsigned)len); + break; + ENDFOR(mf); + break; + case 0x80: // ChapterDisplay + disp = NULL; + + FOREACH(mf,len) + case 0x85: // ChapterString + if (disp==NULL) { + disp = ASGET(mf,ch,Display); + memset(disp, 0, sizeof(*disp)); + } + if (disp->String) + skipbytes(mf,len); // Ignore duplicate string + else + STRGETM(mf,disp->String,len); + break; + case 0x437c: // ChapterLanguage + if (disp==NULL) { + disp = ASGET(mf,ch,Display); + memset(disp, 0, sizeof(*disp)); + } + readLangCC(mf, len, disp->Language); + break; + case 0x437e: // ChapterCountry + if (disp==NULL) { + disp = ASGET(mf,ch,Display); + memset(disp, 0, sizeof(*disp)); + } + readLangCC(mf, len, disp->Country); + break; + ENDFOR(mf); + + if (disp && !disp->String) + --ch->nDisplay; + break; + case 0x6944: // ChapProcess + proc = NULL; + + FOREACH(mf,len) + case 0x6955: // ChapProcessCodecID + if (proc == NULL) { + proc = ASGET(mf, ch, Process); + memset(proc, 0, sizeof(*proc)); + } + proc->CodecID = (unsigned)readUInt(mf,(unsigned)len); + break; + case 0x450d: // ChapProcessPrivate + if (proc == NULL) { + proc = ASGET(mf, ch, Process); + memset(proc, 0, sizeof(*proc)); + } + if (proc->CodecPrivate) + skipbytes(mf, len); + else { + proc->CodecPrivateLength = (unsigned)len; + STRGETM(mf,proc->CodecPrivate,len); + } + break; + case 0x6911: // ChapProcessCommand + if (proc == NULL) { + proc = ASGET(mf, ch, Process); + memset(proc, 0, sizeof(*proc)); + } + + cmd = NULL; + + FOREACH(mf,len) + case 0x6922: // ChapterCommandTime + if (cmd == NULL) { + cmd = ASGET(mf,proc,Commands); + memset(cmd, 0, sizeof(*cmd)); + } + cmd->Time = (unsigned)readUInt(mf,(unsigned)len); + break; + case 0x6933: // ChapterCommandString + if (cmd == NULL) { + cmd = ASGET(mf,proc,Commands); + memset(cmd, 0, sizeof(*cmd)); + } + if (cmd->Command) + skipbytes(mf,len); + else { + cmd->CommandLength = (unsigned)len; + STRGETM(mf,cmd->Command,len); + } + break; + ENDFOR(mf); + + if (cmd && !cmd->Command) + --proc->nCommands; + break; + ENDFOR(mf); + + if (proc && !proc->nCommands) + --ch->nProcess; + break; + case 0xb6: // Nested ChapterAtom + parseChapter(mf,len,ch); + break; + ENDFOR(mf); + + ARELEASE(mf,ch,Tracks); + ARELEASE(mf,ch,Display); + ARELEASE(mf,ch,Children); +} + +static void parseChapters(MatroskaFile *mf,ulonglong toplen) { + struct Chapter *ch; + + mf->seen.Chapters = 1; + + FOREACH(mf,toplen) + case 0x45b9: // EditionEntry + ch = AGET(mf,Chapters); + memset(ch, 0, sizeof(*ch)); + FOREACH(mf,len) + case 0x45bc: // EditionUID + ch->UID = readUInt(mf,(unsigned)len); + break; + case 0x45bd: // EditionFlagHidden + ch->Hidden = readUInt(mf,(unsigned)len)!=0; + break; + case 0x45db: // EditionFlagDefault + ch->Default = readUInt(mf,(unsigned)len)!=0; + break; + case 0x45dd: // EditionFlagOrdered + ch->Ordered = readUInt(mf,(unsigned)len)!=0; + break; + case 0xb6: // ChapterAtom + parseChapter(mf,len,ch); + break; + ENDFOR(mf); + break; + ENDFOR(mf); +} + +static void parseTags(MatroskaFile *mf,ulonglong toplen) { + struct Tag *tag; + struct Target *target; + struct SimpleTag *st; + + mf->seen.Tags = 1; + + FOREACH(mf,toplen) + case 0x7373: // Tag + tag = AGET(mf,Tags); + memset(tag,0,sizeof(*tag)); + + FOREACH(mf,len) + case 0x63c0: // Targets + FOREACH(mf,len) + case 0x63c5: // TrackUID + target = ASGET(mf,tag,Targets); + target->UID = readUInt(mf,(unsigned)len); + target->Type = TARGET_TRACK; + break; + case 0x63c4: // ChapterUID + target = ASGET(mf,tag,Targets); + target->UID = readUInt(mf,(unsigned)len); + target->Type = TARGET_CHAPTER; + break; + case 0x63c6: // AttachmentUID + target = ASGET(mf,tag,Targets); + target->UID = readUInt(mf,(unsigned)len); + target->Type = TARGET_ATTACHMENT; + break; + case 0x63c9: // EditionUID + target = ASGET(mf,tag,Targets); + target->UID = readUInt(mf,(unsigned)len); + target->Type = TARGET_EDITION; + break; + ENDFOR(mf); + break; + case 0x67c8: // SimpleTag + st = ASGET(mf,tag,SimpleTags); + memset(st,0,sizeof(*st)); + + FOREACH(mf,len) + case 0x45a3: // TagName + if (st->Name) + skipbytes(mf,len); + else + STRGETM(mf,st->Name,len); + break; + case 0x4487: // TagString + if (st->Value) + skipbytes(mf,len); + else + STRGETM(mf,st->Value,len); + break; + case 0x447a: // TagLanguage + readLangCC(mf, len, st->Language); + break; + case 0x4484: // TagDefault + st->Default = readUInt(mf,(unsigned)len)!=0; + break; + ENDFOR(mf); + + if (!st->Name || !st->Value) { + mf->cache->memfree(mf->cache,st->Name); + mf->cache->memfree(mf->cache,st->Value); + --tag->nSimpleTags; + } + break; + ENDFOR(mf); + break; + ENDFOR(mf); +} + +static void parseContainer(MatroskaFile *mf) { + ulonglong len; + int id = readID(mf); + if (id==EOF) + errorjmp(mf,"Unexpected EOF in parseContainer"); + + len = readSize(mf); + + switch (id) { + case 0x1549a966: // SegmentInfo + parseSegmentInfo(mf,len); + break; + case 0x1f43b675: // Cluster + parseFirstCluster(mf,len); + break; + case 0x1654ae6b: // Tracks + parseTracks(mf,len); + break; + case 0x1c53bb6b: // Cues + parseCues(mf,len); + break; + case 0x1941a469: // Attachments + parseAttachments(mf,len); + break; + case 0x1043a770: // Chapters + parseChapters(mf,len); + break; + case 0x1254c367: // Tags + parseTags(mf,len); + break; + } +} + +static void parseContainerPos(MatroskaFile *mf,ulonglong pos) { + seek(mf,pos); + parseContainer(mf); +} + +static void parsePointers(MatroskaFile *mf) { + jmp_buf jb; + + if (mf->pSegmentInfo && !mf->seen.SegmentInfo) + parseContainerPos(mf,mf->pSegmentInfo); + if (mf->pCluster && !mf->seen.Cluster) + parseContainerPos(mf,mf->pCluster); + if (mf->pTracks && !mf->seen.Tracks) + parseContainerPos(mf,mf->pTracks); + + memcpy(&jb,&mf->jb,sizeof(jb)); + + if (setjmp(mf->jb)) + mf->flags &= ~MPF_ERROR; // ignore errors + else { + if (mf->pCues && !mf->seen.Cues) + parseContainerPos(mf,mf->pCues); + if (mf->pAttachments && !mf->seen.Attachments) + parseContainerPos(mf,mf->pAttachments); + if (mf->pChapters && !mf->seen.Chapters) + parseContainerPos(mf,mf->pChapters); + if (mf->pTags && !mf->seen.Tags) + parseContainerPos(mf,mf->pTags); + } + + memcpy(&mf->jb,&jb,sizeof(jb)); +} + +static void parseSegment(MatroskaFile *mf,ulonglong toplen) { + ulonglong nextpos; + unsigned nSeekHeads = 0, dontstop = 0; + jmp_buf jb; + + memcpy(&jb,&mf->jb,sizeof(jb)); + + if (setjmp(mf->jb)) + mf->flags &= ~MPF_ERROR; + else { + // we want to read data until we find a seekhead or a trackinfo + FOREACH2(mf,toplen,0x1f43b675) + case 0x114d9b74: // SeekHead + if (mf->flags & MKVF_AVOID_SEEKS) { + skipbytes(mf,len); + break; + } + + nextpos = filepos(mf) + len; + do { + mf->pSeekHead = 0; + parseSeekHead(mf,len); + ++nSeekHeads; + if (mf->pSeekHead) { // this is possibly a chained SeekHead + seek(mf,mf->pSeekHead); + id = readID(mf); + if (id==EOF) // chained SeekHead points to EOF? + break; + if (id != 0x114d9b74) // chained SeekHead doesnt point to a SeekHead? + break; + len = readSize(mf); + } + } while (mf->pSeekHead && nSeekHeads < 10); + seek(mf,nextpos); // resume reading segment + break; + case 0x1549a966: // SegmentInfo + mf->pSegmentInfo = cur; + parseSegmentInfo(mf,len); + break; + case 0x1f43b675: // Cluster + if (!mf->pCluster) + mf->pCluster = cur; + if (mf->seen.Cluster) { + if (len != MAXU64) + skipbytes(mf,len); + } else + parseFirstCluster(mf,len); + break; + case 0x1654ae6b: // Tracks + mf->pTracks = cur; + parseTracks(mf,len); + break; + case 0x1c53bb6b: // Cues + mf->pCues = cur; + parseCues(mf,len); + break; + case 0x1941a469: // Attachments + mf->pAttachments = cur; + parseAttachments(mf,len); + break; + case 0x1043a770: // Chapters + mf->pChapters = cur; + parseChapters(mf,len); + break; + case 0x1254c367: // Tags + mf->pTags = cur; + parseTags(mf,len); + break; + ENDFOR1(mf); + // if we have pointers to all key elements + if (!dontstop && mf->pSegmentInfo && mf->pTracks && mf->pCluster) + break; + ENDFOR2(); + } + + memcpy(&mf->jb,&jb,sizeof(jb)); + + parsePointers(mf); +} + +static void parseBlockAdditions(MatroskaFile *mf, ulonglong toplen, ulonglong timecode, unsigned track) { + ulonglong add_id = 1, add_pos, add_len; + unsigned char have_add; + + FOREACH(mf, toplen) + case 0xa6: // BlockMore + have_add = 0; + FOREACH(mf, len) + case 0xee: // BlockAddId + add_id = readUInt(mf, (unsigned)len); + break; + case 0xa5: // BlockAddition + add_pos = filepos(mf); + add_len = len; + skipbytes(mf, len); + ++have_add; + break; + ENDFOR(mf); + if (have_add == 1 && id > 0 && id < 255) { + struct QueueEntry *qe = QAlloc(mf); + qe->Start = qe->End = timecode; + qe->Position = add_pos; + qe->Length = (unsigned)add_len; + qe->flags = FRAME_UNKNOWN_START | FRAME_UNKNOWN_END | + (((unsigned)add_id << FRAME_STREAM_SHIFT) & FRAME_STREAM_MASK); + + QPut(&mf->Queues[track],qe); + } + break; + ENDFOR(mf); +} + +static void parseBlockGroup(MatroskaFile *mf,ulonglong toplen,ulonglong timecode, int blockex) { + ulonglong v; + ulonglong duration = 0; + ulonglong dpos; + struct QueueEntry *qe,*qf = NULL; + unsigned char have_duration = 0, have_block = 0; + unsigned char gap = 0; + unsigned char lacing = 0; + unsigned char ref = 0; + unsigned char trackid; + unsigned tracknum = 0; + int c; + unsigned nframes = 0,i; + unsigned *sizes; + signed short block_timecode; + + if (blockex) + goto blockex; + + FOREACH(mf,toplen) + case 0xfb: // ReferenceBlock + readSInt(mf,(unsigned)len); + ref = 1; + break; +blockex: + cur = start = filepos(mf); + len = tmplen = toplen; + case 0xa1: // Block + have_block = 1; + + dpos = filepos(mf); + + v = readVLUInt(mf); + if (v>255) + errorjmp(mf,"Invalid track number in Block: %d",(int)v); + trackid = (unsigned char)v; + + for (tracknum=0;tracknumnTracks;++tracknum) + if (mf->Tracks[tracknum]->Number == trackid) { + if (mf->trackMask & (1<Tracks[tracknum]->TimecodeScale, + (timecode - mf->firstTimecode + block_timecode) * mf->Seg.TimecodeScale); + + c = readch(mf); + if (c==EOF) + errorjmp(mf,"Unexpected EOF while reading Block flags"); + + if (blockex) + ref = (unsigned char)!(c & 0x80); + + gap = (unsigned char)(c & 0x1); + lacing = (unsigned char)((c >> 1) & 3); + + if (lacing) { + c = readch(mf); + if (c == EOF) + errorjmp(mf,"Unexpected EOF while reading lacing data"); + nframes = c+1; + } else + nframes = 1; + sizes = alloca(nframes*sizeof(*sizes)); + + switch (lacing) { + case 0: // No lacing + sizes[0] = (unsigned)(len - filepos(mf) + dpos); + break; + case 1: // Xiph lacing + sizes[nframes-1] = 0; + for (i=0;i1) + sizes[nframes-1] = (unsigned)(len - filepos(mf) + dpos) - sizes[0] - sizes[nframes-1]; + break; + case 2: // Fixed lacing + sizes[0] = (unsigned)(len - filepos(mf) + dpos)/nframes; + for (i=1;iStart = timecode; + qe->End = timecode; + qe->Position = v; + qe->Length = sizes[i]; + qe->flags = FRAME_UNKNOWN_END | FRAME_KF; + if (i == nframes-1 && gap) + qe->flags |= FRAME_GAP; + if (i > 0) + qe->flags |= FRAME_UNKNOWN_START; + + QPut(&mf->Queues[tracknum],qe); + + v += sizes[i]; + } + + // we want to still load these bytes into cache + for (v = filepos(mf) & ~0x3fff; v < len + dpos; v += 0x4000) + mf->cache->read(mf->cache,v,NULL,0); // touch page + + skipbytes(mf,len - filepos(mf) + dpos); + + if (blockex) + goto out; + break; + case 0x9b: // BlockDuration + duration = readUInt(mf,(unsigned)len); + have_duration = 1; + break; + case 0x75a1: // BlockAdditions + if (nframes > 0) // have some frames + parseBlockAdditions(mf, len, timecode, tracknum); + else + skipbytes(mf, len); + break; + ENDFOR(mf); + +out: + if (!have_block) + errorjmp(mf,"Found a BlockGroup without Block"); + + if (nframes > 1) { + ulonglong defd = mf->Tracks[tracknum]->DefaultDuration; + v = qf->Start; + + if (have_duration) { + duration = mul3(mf->Tracks[tracknum]->TimecodeScale, + duration * mf->Seg.TimecodeScale); + + for (qe = qf; nframes > 1; --nframes, qe = qe->next) { + qe->Start = v; + v += defd; + duration -= defd; + qe->End = v; +#if 0 + qe->flags &= ~(FRAME_UNKNOWN_START|FRAME_UNKNOWN_END); +#endif + } + qe->Start = v; + qe->End = v + duration; + qe->flags &= ~FRAME_UNKNOWN_END; + } else if (mf->Tracks[tracknum]->DefaultDuration) { + for (qe = qf; nframes > 0; --nframes, qe = qe->next) { + qe->Start = v; + v += defd; + qe->End = v; + qe->flags &= ~(FRAME_UNKNOWN_START|FRAME_UNKNOWN_END); + } + } + } else if (nframes == 1) { + if (have_duration) { + qf->End = qf->Start + mul3(mf->Tracks[tracknum]->TimecodeScale, + duration * mf->Seg.TimecodeScale); + qf->flags &= ~FRAME_UNKNOWN_END; + } else if (mf->Tracks[tracknum]->DefaultDuration) { + qf->End = qf->Start + mf->Tracks[tracknum]->DefaultDuration; + qf->flags &= ~FRAME_UNKNOWN_END; + } + } + + if (ref) + while (qf) { + qf->flags &= ~FRAME_KF; + qf = qf->next; + } +} + +static void ClearQueue(MatroskaFile *mf,struct Queue *q) { + struct QueueEntry *qe,*qn; + + for (qe=q->head;qe;qe=qn) { + qn = qe->next; + qe->next = mf->QFreeList; + mf->QFreeList = qe; + } + + q->head = NULL; + q->tail = NULL; +} + +static void EmptyQueues(MatroskaFile *mf) { + unsigned i; + + for (i=0;inTracks;++i) + ClearQueue(mf,&mf->Queues[i]); +} + +static int readMoreBlocks(MatroskaFile *mf) { + ulonglong toplen, cstop; + longlong cp; + int cid, ret = 0; + jmp_buf jb; + volatile unsigned retries = 0; + + if (mf->readPosition >= mf->pSegmentTop) + return EOF; + + memcpy(&jb,&mf->jb,sizeof(jb)); + + if (setjmp(mf->jb)) { // something evil happened here, try to resync + // always advance read position no matter what so + // we don't get caught in an endless loop + mf->readPosition = filepos(mf); + + ret = EOF; + + if (++retries > 3) // don't try too hard + goto ex; + + for (;;) { + if (filepos(mf) >= mf->pSegmentTop) + goto ex; + + cp = mf->cache->scan(mf->cache,filepos(mf),0x1f43b675); // cluster + + if (cp < 0 || (ulonglong)cp >= mf->pSegmentTop) + goto ex; + + seek(mf,cp); + + cid = readID(mf); + if (cid == EOF) + goto ex; + if (cid == 0x1f43b675) { + toplen = readSizeUnspec(mf); + if (toplen < MAXCLUSTER || toplen == MAXU64) { + // reset error flags + mf->flags &= ~MPF_ERROR; + ret = RBRESYNC; + break; + } + } + } + + mf->readPosition = cp; + } + + cstop = mf->cache->getcachesize(mf->cache)>>1; + if (cstop > MAX_READAHEAD) + cstop = MAX_READAHEAD; + cstop += mf->readPosition; + + seek(mf,mf->readPosition); + + while (filepos(mf) < mf->pSegmentTop) { + cid = readID(mf); + if (cid == EOF) { + ret = EOF; + break; + } + toplen = cid == 0x1f43b675 ? readSizeUnspec(mf) : readSize(mf); + + if (cid == 0x1f43b675) { // Cluster + unsigned char have_timecode = 0; + + FOREACH2(mf,toplen,0x1f43b675) + case 0x1f43b675: + RESTART(); + break; + case 0xe7: // Timecode + mf->tcCluster = readUInt(mf,(unsigned)len); + have_timecode = 1; + break; + case 0xa7: // Position + readUInt(mf,(unsigned)len); + break; + case 0xab: // PrevSize + readUInt(mf,(unsigned)len); + break; + case 0x5854: { // SilentTracks + unsigned stmask = 0, i, trk; + FOREACH(mf, len) + case 0x58d7: // SilentTrackNumber + trk = (unsigned)readUInt(mf, (unsigned)len); + for (i = 0; i < mf->nTracks; ++i) + if (mf->Tracks[i]->Number == trk) { + stmask |= 1 << i; + break; + } + break; + ENDFOR(mf); + // TODO pass stmask to reading app + break; } + case 0xa0: // BlockGroup + if (!have_timecode) + errorjmp(mf,"Found BlockGroup before cluster TimeCode"); + parseBlockGroup(mf,len,mf->tcCluster, 0); + goto out; + case 0xa3: // BlockEx + if (!have_timecode) + errorjmp(mf,"Found BlockGroup before cluster TimeCode"); + parseBlockGroup(mf, len, mf->tcCluster, 1); + goto out; + ENDFOR(mf); +out:; + } else { + if (toplen > MAXFRAME) + errorjmp(mf,"Element in a cluster is too large around %llu, %X [%u]",filepos(mf),cid,(unsigned)toplen); + if (cid == 0xa0) // BlockGroup + parseBlockGroup(mf,toplen,mf->tcCluster, 0); + else if (cid == 0xa3) // BlockEx + parseBlockGroup(mf, toplen, mf->tcCluster, 1); + else + skipbytes(mf,toplen); + } + + if ((mf->readPosition = filepos(mf)) > cstop) + break; + } + + mf->readPosition = filepos(mf); + +ex: + memcpy(&mf->jb,&jb,sizeof(jb)); + + return ret; +} + +// this is almost the same as readMoreBlocks, except it ensures +// there are no partial frames queued, however empty queues are ok +static int fillQueues(MatroskaFile *mf,unsigned int mask) { + unsigned i,j; + int ret = 0; + + for (;;) { + j = 0; + + for (i=0;inTracks;++i) + if (mf->Queues[i].head && !(mask & (1<0) // have at least some frames + return ret; + + if ((ret = readMoreBlocks(mf)) < 0) { + j = 0; + for (i=0;inTracks;++i) + if (mf->Queues[i].head && !(mask & (1<pCluster; + ulonglong step = 10*1024*1024; + ulonglong size, tc, isize; + longlong next_cluster; + int id, have_tc, bad; + struct Cue *cue; + + if (pos >= mf->pSegmentTop) + return; + + if (pos + step * 10 > mf->pSegmentTop) + step = (mf->pSegmentTop - pos) / 10; + if (step == 0) + step = 1; + + memcpy(&jb,&mf->jb,sizeof(jb)); + + // remove all cues + mf->nCues = 0; + + bad = 0; + + while (pos < mf->pSegmentTop) { + if (!mf->cache->progress(mf->cache,pos,mf->pSegmentTop)) + break; + + if (++bad > 50) { + pos += step; + bad = 0; + continue; + } + + // find next cluster header + next_cluster = mf->cache->scan(mf->cache,pos,0x1f43b675); // cluster + if (next_cluster < 0 || (ulonglong)next_cluster >= mf->pSegmentTop) + break; + + pos = next_cluster + 4; // prevent endless loops + + if (setjmp(mf->jb)) // something evil happened while reindexing + continue; + + seek(mf,next_cluster); + + id = readID(mf); + if (id == EOF) + break; + if (id != 0x1f43b675) // shouldn't happen + continue; + + size = readSizeUnspec(mf); + if (size == MAXU64) + break; + + if (size >= MAXCLUSTER || size < 1024) + continue; + + have_tc = 0; + size += filepos(mf); + + while (filepos(mf) < (ulonglong)next_cluster + 1024) { + id = readID(mf); + if (id == EOF) + break; + + isize = readVLUInt(mf); + + if (id == 0xe7) { // cluster timecode + tc = readUInt(mf,(unsigned)isize); + have_tc = 1; + break; + } + + skipbytes(mf,isize); + } + + if (!have_tc) + continue; + + seek(mf,size); + id = readID(mf); + + if (id == EOF) + break; + + if (id != 0x1f43b675) // cluster + continue; + + // good cluster, remember it + cue = AGET(mf,Cues); + cue->Time = tc; + cue->Position = next_cluster - mf->pSegment; + cue->Block = 0; + cue->Track = 0; + + // advance to the next point + pos = next_cluster + step; + if (pos < size) + pos = size; + + bad = 0; + } + + fixupCues(mf); + + if (mf->nCues == 0) { + cue = AGET(mf,Cues); + cue->Time = mf->firstTimecode; + cue->Position = mf->pCluster - mf->pSegment; + cue->Block = 0; + cue->Track = 0; + } + + mf->cache->progress(mf->cache,0,0); + + memcpy(&mf->jb,&jb,sizeof(jb)); +} + +static void fixupChapter(ulonglong adj, struct Chapter *ch) { + unsigned i; + + if (ch->Start != 0) + ch->Start -= adj; + if (ch->End != 0) + ch->End -= adj; + + for (i=0;inChildren;++i) + fixupChapter(adj,&ch->Children[i]); +} + +static longlong findLastTimecode(MatroskaFile *mf) { + ulonglong nd = 0; + unsigned n,vtrack; + + if (mf->nTracks == 0) + return -1; + + for (n=vtrack=0;nnTracks;++n) + if (mf->Tracks[n]->Type == TT_VIDEO) { + vtrack = n; + goto ok; + } + + return -1; +ok: + + EmptyQueues(mf); + + if (mf->nCues == 0) { + mf->readPosition = mf->pCluster + 13000000 > mf->pSegmentTop ? mf->pCluster : mf->pSegmentTop - 13000000; + mf->tcCluster = 0; + } else { + mf->readPosition = mf->Cues[mf->nCues - 1].Position + mf->pSegment; + mf->tcCluster = mf->Cues[mf->nCues - 1].Time / mf->Seg.TimecodeScale; + } + mf->trackMask = ~(1 << vtrack); + + do + while (mf->Queues[vtrack].head) + { + ulonglong tc = mf->Queues[vtrack].head->flags & FRAME_UNKNOWN_END ? + mf->Queues[vtrack].head->Start : mf->Queues[vtrack].head->End; + if (nd < tc) + nd = tc; + QFree(mf,QGet(&mf->Queues[vtrack])); + } + while (fillQueues(mf,0) != EOF); + + mf->trackMask = 0; + + EmptyQueues(mf); + + // there may have been an error, but at this point we will ignore it + if (mf->flags & MPF_ERROR) { + mf->flags &= ~MPF_ERROR; + if (nd == 0) + return -1; + } + + return nd; +} + +static void parseFile(MatroskaFile *mf) { + ulonglong len = filepos(mf), adjust; + unsigned i; + int id = readID(mf); + + if (id==EOF) + errorjmp(mf,"Unexpected EOF at start of file"); + + // files with multiple concatenated segments can have only + // one EBML prolog + if (len > 0 && id == 0x18538067) + goto segment; + + if (id!=0x1a45dfa3) + errorjmp(mf,"First element in file is not EBML"); + + parseEBML(mf,readSize(mf)); + + // next we need to find the first segment + for (;;) { + id = readID(mf); + if (id==EOF) + errorjmp(mf,"No segments found in the file"); +segment: + len = readSizeUnspec(mf); + if (id == 0x18538067) // Segment + break; + if (len == MAXU64) + errorjmp(mf,"No segments found in the file"); + skipbytes(mf,len); + } + + // found it + mf->pSegment = filepos(mf); + if (len == MAXU64) { + mf->pSegmentTop = MAXU64; + if (mf->cache->getfilesize) { + longlong seglen = mf->cache->getfilesize(mf->cache); + if (seglen > 0) + mf->pSegmentTop = seglen; + } + } else + mf->pSegmentTop = mf->pSegment + len; + parseSegment(mf,len); + + // check if we got all data + if (!mf->seen.SegmentInfo) + errorjmp(mf,"Couldn't find SegmentInfo"); + if (!mf->seen.Cluster) + mf->pCluster = mf->pSegmentTop; + + adjust = mf->firstTimecode * mf->Seg.TimecodeScale; + + for (i=0;inChapters;++i) + fixupChapter(adjust, &mf->Chapters[i]); + + fixupCues(mf); + + // release extra memory + ARELEASE(mf,mf,Tracks); + + // initialize reader + mf->Queues = mf->cache->memalloc(mf->cache,mf->nTracks * sizeof(*mf->Queues)); + if (mf->Queues == NULL) + errorjmp(mf, "Ouf of memory"); + memset(mf->Queues, 0, mf->nTracks * sizeof(*mf->Queues)); + + // try to detect real duration + if (!(mf->flags & MKVF_AVOID_SEEKS)) { + longlong nd = findLastTimecode(mf); + if (nd > 0) + mf->Seg.Duration = nd; + } + + // move to first frame + mf->readPosition = mf->pCluster; + mf->tcCluster = mf->firstTimecode; +} + +static void DeleteChapter(MatroskaFile *mf,struct Chapter *ch) { + unsigned i,j; + + for (i=0;inDisplay;++i) + mf->cache->memfree(mf->cache,ch->Display[i].String); + mf->cache->memfree(mf->cache,ch->Display); + mf->cache->memfree(mf->cache,ch->Tracks); + + for (i=0;inProcess;++i) { + for (j=0;jProcess[i].nCommands;++j) + mf->cache->memfree(mf->cache,ch->Process[i].Commands[j].Command); + mf->cache->memfree(mf->cache,ch->Process[i].Commands); + mf->cache->memfree(mf->cache,ch->Process[i].CodecPrivate); + } + mf->cache->memfree(mf->cache,ch->Process); + + for (i=0;inChildren;++i) + DeleteChapter(mf,&ch->Children[i]); + mf->cache->memfree(mf->cache,ch->Children); +} + +/////////////////////////////////////////////////////////////////////////// +// public interface +MatroskaFile *mkv_OpenEx(InputStream *io, + ulonglong base, + unsigned flags, + char *err_msg,unsigned msgsize) +{ + MatroskaFile *mf = io->memalloc(io,sizeof(*mf)); + if (mf == NULL) { + mystrlcpy(err_msg,"Out of memory",msgsize); + return NULL; + } + + memset(mf,0,sizeof(*mf)); + + mf->cache = io; + mf->flags = flags; + io->progress(io,0,0); + + if (setjmp(mf->jb)==0) { + seek(mf,base); + parseFile(mf); + } else { // parser error + mystrlcpy(err_msg,mf->errmsg,msgsize); + mkv_Close(mf); + return NULL; + } + + return mf; +} + +MatroskaFile *mkv_Open(InputStream *io, + char *err_msg,unsigned msgsize) +{ + return mkv_OpenEx(io,0,0,err_msg,msgsize); +} + +void mkv_Close(MatroskaFile *mf) { + unsigned i,j; + + if (mf==NULL) + return; + + for (i=0;inTracks;++i) + mf->cache->memfree(mf->cache,mf->Tracks[i]); + mf->cache->memfree(mf->cache,mf->Tracks); + + for (i=0;inQBlocks;++i) + mf->cache->memfree(mf->cache,mf->QBlocks[i]); + mf->cache->memfree(mf->cache,mf->QBlocks); + + mf->cache->memfree(mf->cache,mf->Queues); + + mf->cache->memfree(mf->cache,mf->Seg.Title); + mf->cache->memfree(mf->cache,mf->Seg.MuxingApp); + mf->cache->memfree(mf->cache,mf->Seg.WritingApp); + mf->cache->memfree(mf->cache,mf->Seg.Filename); + mf->cache->memfree(mf->cache,mf->Seg.NextFilename); + mf->cache->memfree(mf->cache,mf->Seg.PrevFilename); + + mf->cache->memfree(mf->cache,mf->Cues); + + for (i=0;inAttachments;++i) { + mf->cache->memfree(mf->cache,mf->Attachments[i].Description); + mf->cache->memfree(mf->cache,mf->Attachments[i].Name); + mf->cache->memfree(mf->cache,mf->Attachments[i].MimeType); + } + mf->cache->memfree(mf->cache,mf->Attachments); + + for (i=0;inChapters;++i) + DeleteChapter(mf,&mf->Chapters[i]); + mf->cache->memfree(mf->cache,mf->Chapters); + + for (i=0;inTags;++i) { + for (j=0;jTags[i].nSimpleTags;++j) { + mf->cache->memfree(mf->cache,mf->Tags[i].SimpleTags[j].Name); + mf->cache->memfree(mf->cache,mf->Tags[i].SimpleTags[j].Value); + } + mf->cache->memfree(mf->cache,mf->Tags[i].Targets); + mf->cache->memfree(mf->cache,mf->Tags[i].SimpleTags); + } + mf->cache->memfree(mf->cache,mf->Tags); + + mf->cache->memfree(mf->cache,mf); +} + +const char *mkv_GetLastError(MatroskaFile *mf) { + return mf->errmsg[0] ? mf->errmsg : NULL; +} + +SegmentInfo *mkv_GetFileInfo(MatroskaFile *mf) { + return &mf->Seg; +} + +unsigned int mkv_GetNumTracks(MatroskaFile *mf) { + return mf->nTracks; +} + +TrackInfo *mkv_GetTrackInfo(MatroskaFile *mf,unsigned track) { + if (track>mf->nTracks) + return NULL; + + return mf->Tracks[track]; +} + +void mkv_GetAttachments(MatroskaFile *mf,Attachment **at,unsigned *count) { + *at = mf->Attachments; + *count = mf->nAttachments; +} + +void mkv_GetChapters(MatroskaFile *mf,Chapter **ch,unsigned *count) { + *ch = mf->Chapters; + *count = mf->nChapters; +} + +void mkv_GetTags(MatroskaFile *mf,Tag **tag,unsigned *count) { + *tag = mf->Tags; + *count = mf->nTags; +} + +ulonglong mkv_GetSegmentTop(MatroskaFile *mf) { + return mf->pSegmentTop; +} + +#define IS_DELTA(f) (!((f)->flags & FRAME_KF) || ((f)->flags & FRAME_UNKNOWN_START)) + +void mkv_Seek(MatroskaFile *mf,ulonglong timecode,unsigned flags) { + int i,j,m,ret; + unsigned n,z,mask; + ulonglong m_kftime[MAX_TRACKS]; + unsigned char m_seendf[MAX_TRACKS]; + + if (mf->flags & MKVF_AVOID_SEEKS) + return; + + if (timecode == 0) { + EmptyQueues(mf); + mf->readPosition = mf->pCluster; + mf->tcCluster = mf->firstTimecode; + mf->flags &= ~MPF_ERROR; + + return; + } + + if (mf->nCues==0) + reindex(mf); + + if (mf->nCues==0) + return; + + mf->flags &= ~MPF_ERROR; + + i = 0; + j = mf->nCues - 1; + + for (;;) { + if (i>j) { + j = j>=0 ? j : 0; + + if (setjmp(mf->jb)!=0) + return; + + mkv_SetTrackMask(mf,mf->trackMask); + + if (flags & (MKVF_SEEK_TO_PREV_KEYFRAME | MKVF_SEEK_TO_PREV_KEYFRAME_STRICT)) { + // we do this in two stages + // a. find the last keyframes before the require position + // b. seek to them + + // pass 1 + for (;;) { + for (n=0;nnTracks;++n) { + m_kftime[n] = MAXU64; + m_seendf[n] = 0; + } + + EmptyQueues(mf); + + mf->readPosition = mf->Cues[j].Position + mf->pSegment; + mf->tcCluster = mf->Cues[j].Time; + + for (;;) { + if ((ret = fillQueues(mf,0)) < 0 || ret == RBRESYNC) + return; + + // drain queues until we get to the required timecode + for (n=0;nnTracks;++n) { + if (mf->Queues[n].head && (mf->Queues[n].head->StartQueues[n].head)) + m_seendf[n] = 1; + else + m_kftime[n] = mf->Queues[n].head->Start; + } + + while (mf->Queues[n].head && mf->Queues[n].head->StartQueues[n].head)) + m_seendf[n] = 1; + else + m_kftime[n] = mf->Queues[n].head->Start; + QFree(mf,QGet(&mf->Queues[n])); + } + + // We've drained the queue, so the frame at head is the next one past the requered point. + // In strict mode we are done, but when seeking is not strict we use the head frame + // if it's not an audio track (we accept preroll within a frame for audio), and the head frame + // is a keyframe + if (!(flags & MKVF_SEEK_TO_PREV_KEYFRAME_STRICT)) + if (mf->Queues[n].head && (mf->Tracks[n]->Type != TT_AUDIO || mf->Queues[n].head->Start<=timecode)) + if (!IS_DELTA(mf->Queues[n].head)) + m_kftime[n] = mf->Queues[n].head->Start; + } + + for (n=0;nnTracks;++n) + if (mf->Queues[n].head && mf->Queues[n].head->Start>=timecode) + goto found; + } +found: + + for (n=0;nnTracks;++n) + if (!(mf->trackMask & (1<0) + { + // we need to restart the search from prev cue + --j; + goto again; + } + + break; +again:; + } + } else + for (n=0;nnTracks;++n) + m_kftime[n] = timecode; + + // now seek to this timecode + EmptyQueues(mf); + + mf->readPosition = mf->Cues[j].Position + mf->pSegment; + mf->tcCluster = mf->Cues[j].Time; + + for (mask=0;;) { + if ((ret = fillQueues(mf,mask)) < 0 || ret == RBRESYNC) + return; + + // drain queues until we get to the required timecode + for (n=0;nnTracks;++n) { + struct QueueEntry *qe; + for (qe = mf->Queues[n].head;qe && qe->StartQueues[n].head) + QFree(mf,QGet(&mf->Queues[n])); + } + + for (n=z=0;nnTracks;++n) + if (m_kftime[n]==MAXU64 || (mf->Queues[n].head && mf->Queues[n].head->Start>=m_kftime[n])) { + ++z; + mask |= 1<nTracks) + return; + } + } + + m = (i+j)>>1; + + if (timecode < mf->Cues[m].Time) + j = m-1; + else + i = m+1; + } +} + +void mkv_SkipToKeyframe(MatroskaFile *mf) { + unsigned n,wait; + ulonglong ht; + + if (setjmp(mf->jb)!=0) + return; + + // remove delta frames from queues + do { + wait = 0; + + if (fillQueues(mf,0)<0) + return; + + for (n=0;nnTracks;++n) + if (mf->Queues[n].head && !(mf->Queues[n].head->flags & FRAME_KF)) { + ++wait; + QFree(mf,QGet(&mf->Queues[n])); + } + } while (wait); + + // find highest queued time + for (n=0,ht=0;nnTracks;++n) + if (mf->Queues[n].head && htQueues[n].head->Start) + ht = mf->Queues[n].head->Start; + + // ensure the time difference is less than 100ms + do { + wait = 0; + + if (fillQueues(mf,0)<0) + return; + + for (n=0;nnTracks;++n) + while (mf->Queues[n].head && mf->Queues[n].head->next && + (mf->Queues[n].head->next->flags & FRAME_KF) && + ht - mf->Queues[n].head->Start > 100000000) + { + ++wait; + QFree(mf,QGet(&mf->Queues[n])); + } + + } while (wait); +} + +ulonglong mkv_GetLowestQTimecode(MatroskaFile *mf) { + unsigned n,seen; + ulonglong t; + + // find the lowest queued timecode + for (n=seen=0,t=0;nnTracks;++n) + if (mf->Queues[n].head && (!seen || t > mf->Queues[n].head->Start)) + t = mf->Queues[n].head->Start, seen=1; + + return seen ? t : (ulonglong)LL(-1); +} + +int mkv_TruncFloat(MKFLOAT f) { +#ifdef MATROSKA_INTEGER_ONLY + return (int)(f.v >> 32); +#else + return (int)f; +#endif +} + +#define FTRACK 0xffffffff + +void mkv_SetTrackMask(MatroskaFile *mf,unsigned int mask) { + unsigned int i; + + if (mf->flags & MPF_ERROR) + return; + + mf->trackMask = mask; + + for (i=0;inTracks;++i) + if (mask & (1<Queues[i]); +} + +int mkv_ReadFrame(MatroskaFile *mf, + unsigned int mask,unsigned int *track, + ulonglong *StartTime,ulonglong *EndTime, + ulonglong *FilePos,unsigned int *FrameSize, + unsigned int *FrameFlags) +{ + unsigned int i,j; + struct QueueEntry *qe; + + if (setjmp(mf->jb)!=0) + return -1; + + do { + // extract required frame, use block with the lowest timecode + for (j=FTRACK,i=0;inTracks;++i) + if (!(mask & (1<Queues[i].head) { + j = i; + ++i; + break; + } + + for (;inTracks;++i) + if (!(mask & (1<Queues[i].head && + mf->Queues[j].head->Start > mf->Queues[i].head->Start) + j = i; + + if (j != FTRACK) { + qe = QGet(&mf->Queues[j]); + + *track = j; + *StartTime = qe->Start; + *EndTime = qe->End; + *FilePos = qe->Position; + *FrameSize = qe->Length; + *FrameFlags = qe->flags; + + QFree(mf,qe); + + return 0; + } + + if (mf->flags & MPF_ERROR) + return -1; + + } while (fillQueues(mf,mask)>=0); + + return EOF; +} + +#ifdef MATROSKA_COMPRESSION_SUPPORT +/************************************************************************* + * Compressed streams support + ************************************************************************/ +struct CompressedStream { + MatroskaFile *mf; + z_stream zs; + + /* current compressed frame */ + ulonglong frame_pos; + unsigned frame_size; + char frame_buffer[2048]; + + /* decoded data buffer */ + char decoded_buffer[2048]; + unsigned decoded_ptr; + unsigned decoded_size; + + /* error handling */ + char errmsg[128]; +}; + +CompressedStream *cs_Create(/* in */ MatroskaFile *mf, + /* in */ unsigned tracknum, + /* out */ char *errormsg, + /* in */ unsigned msgsize) +{ + CompressedStream *cs; + TrackInfo *ti; + int code; + + ti = mkv_GetTrackInfo(mf, tracknum); + if (ti == NULL) { + mystrlcpy(errormsg, "No such track.", msgsize); + return NULL; + } + + if (!ti->CompEnabled) { + mystrlcpy(errormsg, "Track is not compressed.", msgsize); + return NULL; + } + + if (ti->CompMethod != COMP_ZLIB) { + mystrlcpy(errormsg, "Unsupported compression method.", msgsize); + return NULL; + } + + cs = mf->cache->memalloc(mf->cache,sizeof(*cs)); + if (cs == NULL) { + mystrlcpy(errormsg, "Ouf of memory.", msgsize); + return NULL; + } + + memset(&cs->zs,0,sizeof(cs->zs)); + code = inflateInit(&cs->zs); + if (code != Z_OK) { + mystrlcpy(errormsg, "ZLib error.", msgsize); + mf->cache->memfree(mf->cache,cs); + return NULL; + } + + cs->frame_size = 0; + cs->decoded_ptr = cs->decoded_size = 0; + cs->mf = mf; + + return cs; +} + +void cs_Destroy(/* in */ CompressedStream *cs) { + if (cs == NULL) + return; + + inflateEnd(&cs->zs); + cs->mf->cache->memfree(cs->mf->cache,cs); +} + +/* advance to the next frame in matroska stream, you need to pass values returned + * by mkv_ReadFrame */ +void cs_NextFrame(/* in */ CompressedStream *cs, + /* in */ ulonglong pos, + /* in */ unsigned size) +{ + cs->zs.avail_in = 0; + inflateReset(&cs->zs); + cs->frame_pos = pos; + cs->frame_size = size; + cs->decoded_ptr = cs->decoded_size = 0; +} + +/* read and decode more data from current frame, return number of bytes decoded, + * 0 on end of frame, or -1 on error */ +int cs_ReadData(CompressedStream *cs,char *buffer,unsigned bufsize) +{ + char *cp = buffer; + unsigned rd = 0; + unsigned todo; + int code; + + do { + /* try to copy data from decoded buffer */ + if (cs->decoded_ptr < cs->decoded_size) { + todo = cs->decoded_size - cs->decoded_ptr;; + if (todo > bufsize - rd) + todo = bufsize - rd; + + memcpy(cp, cs->decoded_buffer + cs->decoded_ptr, todo); + + rd += todo; + cp += todo; + cs->decoded_ptr += todo; + } else { + /* setup output buffer */ + cs->zs.next_out = (Bytef *)cs->decoded_buffer; + cs->zs.avail_out = sizeof(cs->decoded_buffer); + + /* try to read more data */ + if (cs->zs.avail_in == 0 && cs->frame_size > 0) { + todo = cs->frame_size; + if (todo > sizeof(cs->frame_buffer)) + todo = sizeof(cs->frame_buffer); + + if (cs->mf->cache->read(cs->mf->cache, cs->frame_pos, cs->frame_buffer, todo) != (int)todo) { + mystrlcpy(cs->errmsg, "File read failed", sizeof(cs->errmsg)); + return -1; + } + + cs->zs.next_in = (Bytef *)cs->frame_buffer; + cs->zs.avail_in = todo; + + cs->frame_pos += todo; + cs->frame_size -= todo; + } + + /* try to decode more data */ + code = inflate(&cs->zs,Z_NO_FLUSH); + if (code != Z_OK && code != Z_STREAM_END) { + mystrlcpy(cs->errmsg, "ZLib error.", sizeof(cs->errmsg)); + return -1; + } + + /* handle decoded data */ + if (cs->zs.avail_out == sizeof(cs->decoded_buffer)) /* EOF */ + break; + + cs->decoded_ptr = 0; + cs->decoded_size = sizeof(cs->decoded_buffer) - cs->zs.avail_out; + } + } while (rd < bufsize); + + return rd; +} + +/* return error message for the last error */ +const char *cs_GetLastError(CompressedStream *cs) +{ + if (!cs->errmsg[0]) + return NULL; + return cs->errmsg; +} +#endif diff --git a/MP42/muxer/MatroskaParser.h b/MP42/muxer/MatroskaParser.h new file mode 100644 index 0000000..b3e1f75 --- /dev/null +++ b/MP42/muxer/MatroskaParser.h @@ -0,0 +1,396 @@ +/* + * Copyright (c) 2004-2008 Mike Matsnev. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice immediately at the beginning of the file, without modification, + * this list of conditions, and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Absolutely no warranty of function or purpose is made by the author + * Mike Matsnev. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: MatroskaParser.h,v 1.22 2008/04/29 21:03:09 mike Exp $ + * + */ + +#ifndef MATROSKA_PARSER_H +#define MATROSKA_PARSER_H + +/* Random notes: + * + * The parser does not process frame data in any way and does not read it into + * the queue. The app should read it via mkv_ReadData if it is interested. + * + * The code here is 64-bit clean and was tested on FreeBSD/sparc 64-bit big endian + * system + */ + +#ifdef MPDLLBUILD +#define X __declspec(dllexport) +#else +#ifdef MPDLL +#define X __declspec(dllimport) +#pragma comment(lib,"MatroskaParser") +#else +#define X +#endif +#endif + +#define MATROSKA_COMPRESSION_SUPPORT +#define MATROSKA_INTEGER_ONLY + +#ifdef __cplusplus +extern "C" { +#endif + +/* 64-bit integers */ +#ifdef _WIN32_WCE +typedef signed __int64 longlong; +typedef unsigned __int64 ulonglong; +#else +typedef signed long long longlong; +typedef unsigned long long ulonglong; +#endif + +/* MKFLOATing point */ +#ifdef MATROSKA_INTEGER_ONLY +typedef struct { + longlong v; +} MKFLOAT; +#else +typedef double MKFLOAT; +#endif + +/* generic I/O */ +struct InputStream { + /* read bytes from stream */ + int (*read)(struct InputStream *cc,ulonglong pos,void *buffer,int count); + /* scan for a four byte signature, bytes must be nonzero */ + longlong (*scan)(struct InputStream *cc,ulonglong start,unsigned signature); + /* get cache size, this is used to cap readahead */ + unsigned (*getcachesize)(struct InputStream *cc); + /* fetch last error message */ + const char *(*geterror)(struct InputStream *cc); + /* memory allocation */ + void *(*memalloc)(struct InputStream *cc,size_t size); + void *(*memrealloc)(struct InputStream *cc,void *mem,size_t newsize); + void (*memfree)(struct InputStream *cc,void *mem); + /* zero return causes parser to abort open */ + int (*progress)(struct InputStream *cc,ulonglong cur,ulonglong max); + /* get file size, optional, can be NULL or return -1 if filesize is unknown */ + longlong (*getfilesize)(struct InputStream *cc); +}; + +typedef struct InputStream InputStream; + +/* matroska file */ +struct MatroskaFile; /* opaque */ + +typedef struct MatroskaFile MatroskaFile; + +#define COMP_ZLIB 0 +#define COMP_BZIP 1 +#define COMP_LZO1X 2 +#define COMP_PREPEND 3 + +#define TT_VIDEO 1 +#define TT_AUDIO 2 +#define TT_SUB 17 + +struct TrackInfo { + unsigned char Number; + unsigned char Type; + unsigned char TrackOverlay; + ulonglong UID; + ulonglong MinCache; + ulonglong MaxCache; + ulonglong DefaultDuration; + MKFLOAT TimecodeScale; + void *CodecPrivate; + unsigned CodecPrivateSize; + unsigned CompMethod; + void *CompMethodPrivate; + unsigned CompMethodPrivateSize; + unsigned MaxBlockAdditionID; + + unsigned int Enabled:1; + unsigned int Default:1; + unsigned int Lacing:1; + unsigned int DecodeAll:1; + unsigned int CompEnabled:1; + + union { + struct { + unsigned char StereoMode; + unsigned char DisplayUnit; + unsigned char AspectRatioType; + unsigned int PixelWidth; + unsigned int PixelHeight; + unsigned int DisplayWidth; + unsigned int DisplayHeight; + unsigned int CropL, CropT, CropR, CropB; + unsigned int ColourSpace; + MKFLOAT GammaValue; + + unsigned int Interlaced:1; + } Video; + struct { + MKFLOAT SamplingFreq; + MKFLOAT OutputSamplingFreq; + unsigned char Channels; + unsigned char BitDepth; + } Audio; + } AV; + + /* various strings */ + char *Name; + char Language[4]; + char *CodecID; +}; + +typedef struct TrackInfo TrackInfo; + +struct SegmentInfo { + char UID[16]; + char PrevUID[16]; + char NextUID[16]; + char *Filename; + char *PrevFilename; + char *NextFilename; + char *Title; + char *MuxingApp; + char *WritingApp; + ulonglong TimecodeScale; + ulonglong Duration; + longlong DateUTC; + char DateUTCValid; +}; + +typedef struct SegmentInfo SegmentInfo; + +struct Attachment { + ulonglong Position; + ulonglong Length; + ulonglong UID; + char *Name; + char *Description; + char *MimeType; +}; + +typedef struct Attachment Attachment; + +struct ChapterDisplay { + char *String; + char Language[4]; + char Country[4]; +}; + +struct ChapterCommand { + unsigned Time; + unsigned CommandLength; + void *Command; +}; + +struct ChapterProcess { + unsigned CodecID; + unsigned CodecPrivateLength; + void *CodecPrivate; + unsigned nCommands,nCommandsSize; + struct ChapterCommand *Commands; +}; + +struct Chapter { + ulonglong UID; + ulonglong Start; + ulonglong End; + + unsigned nTracks,nTracksSize; + ulonglong *Tracks; + unsigned nDisplay,nDisplaySize; + struct ChapterDisplay *Display; + unsigned nChildren,nChildrenSize; + struct Chapter *Children; + unsigned nProcess,nProcessSize; + struct ChapterProcess *Process; + + char SegmentUID[16]; + + unsigned int Hidden:1; + unsigned int Enabled:1; + + // Editions + unsigned int Default:1; + unsigned int Ordered:1; +}; + +typedef struct Chapter Chapter; + +#define TARGET_TRACK 0 +#define TARGET_CHAPTER 1 +#define TARGET_ATTACHMENT 2 +#define TARGET_EDITION 3 +struct Target { + ulonglong UID; + unsigned Type; +}; + +struct SimpleTag { + char *Name; + char *Value; + char Language[4]; + unsigned Default:1; +}; + +struct Tag { + unsigned nTargets,nTargetsSize; + struct Target *Targets; + + unsigned nSimpleTags,nSimpleTagsSize; + struct SimpleTag *SimpleTags; +}; + +typedef struct Tag Tag; + +/* Open a matroska file + * io pointer is recorded inside MatroskaFile + */ +X MatroskaFile *mkv_Open(/* in */ InputStream *io, + /* out */ char *err_msg, + /* in */ unsigned msgsize); + +#define MKVF_AVOID_SEEKS 1 /* use sequential reading only */ + +X MatroskaFile *mkv_OpenEx(/* in */ InputStream *io, + /* in */ ulonglong base, + /* in */ unsigned flags, + /* out */ char *err_msg, + /* in */ unsigned msgsize); + +/* Close and deallocate mf + * NULL pointer is ok and is simply ignored + */ +X void mkv_Close(/* in */ MatroskaFile *mf); + +/* Fetch the error message of the last failed operation */ +X const char *mkv_GetLastError(/* in */ MatroskaFile *mf); + +/* Get file information */ +X SegmentInfo *mkv_GetFileInfo(/* in */ MatroskaFile *mf); + +/* Get track information */ +X unsigned int mkv_GetNumTracks(/* in */ MatroskaFile *mf); +X TrackInfo *mkv_GetTrackInfo(/* in */ MatroskaFile *mf,/* in */ unsigned track); + +/* chapters, tags and attachments */ +X void mkv_GetAttachments(/* in */ MatroskaFile *mf, + /* out */ Attachment **at, + /* out */ unsigned *count); +X void mkv_GetChapters(/* in */ MatroskaFile *mf, + /* out */ Chapter **ch, + /* out */ unsigned *count); +X void mkv_GetTags(/* in */ MatroskaFile *mf, + /* out */ Tag **tag, + /* out */ unsigned *count); + +X ulonglong mkv_GetSegmentTop(MatroskaFile *mf); + +/* Seek to specified timecode, + * if timecode is past end of file, + * all tracks are set to return EOF + * on next read + */ +#define MKVF_SEEK_TO_PREV_KEYFRAME 1 +#define MKVF_SEEK_TO_PREV_KEYFRAME_STRICT 2 + +X void mkv_Seek(/* in */ MatroskaFile *mf, + /* in */ ulonglong timecode /* in ns */, + /* in */ unsigned flags); + +X void mkv_SkipToKeyframe(MatroskaFile *mf); + +X ulonglong mkv_GetLowestQTimecode(MatroskaFile *mf); + +X int mkv_TruncFloat(MKFLOAT f); + +/************************************************************************* + * reading data, pull model + */ + +/* frame flags */ +#define FRAME_UNKNOWN_START 0x00000001 +#define FRAME_UNKNOWN_END 0x00000002 +#define FRAME_KF 0x00000004 +#define FRAME_GAP 0x00800000 +#define FRAME_STREAM_MASK 0xff000000 +#define FRAME_STREAM_SHIFT 24 + +/* This sets the masking flags for the parser, + * masked tracks [with 1s in their bit positions] + * will be ignored when reading file data. + * This call discards all parsed and queued frames + */ +X void mkv_SetTrackMask(/* in */ MatroskaFile *mf,/* in */ unsigned int mask); + +/* Read one frame from the queue. + * mask specifies what tracks to ignore. + * Returns -1 if there are no more frames in the specified + * set of tracks, 0 on success + */ +X int mkv_ReadFrame(/* in */ MatroskaFile *mf, + /* in */ unsigned int mask, + /* out */ unsigned int *track, + /* out */ ulonglong *StartTime /* in ns */, + /* out */ ulonglong *EndTime /* in ns */, + /* out */ ulonglong *FilePos /* in bytes from start of file */, + /* out */ unsigned int *FrameSize /* in bytes */, + /* out */ unsigned int *FrameFlags); + +#ifdef MATROSKA_COMPRESSION_SUPPORT +/* Compressed streams support */ +struct CompressedStream; + +typedef struct CompressedStream CompressedStream; + +X CompressedStream *cs_Create(/* in */ MatroskaFile *mf, + /* in */ unsigned tracknum, + /* out */ char *errormsg, + /* in */ unsigned msgsize); +X void cs_Destroy(/* in */ CompressedStream *cs); + +/* advance to the next frame in matroska stream, you need to pass values returned + * by mkv_ReadFrame */ +X void cs_NextFrame(/* in */ CompressedStream *cs, + /* in */ ulonglong pos, + /* in */ unsigned size); + +/* read and decode more data from current frame, return number of bytes decoded, + * 0 on end of frame, or -1 on error */ +X int cs_ReadData(CompressedStream *cs,char *buffer,unsigned bufsize); + +/* return error message for the last error */ +X const char *cs_GetLastError(CompressedStream *cs); +#endif + +#ifdef __cplusplus +} +#endif + +#undef X + +#endif diff --git a/MP42/muxer/downmix.c b/MP42/muxer/downmix.c new file mode 100644 index 0000000..1e40642 --- /dev/null +++ b/MP42/muxer/downmix.c @@ -0,0 +1,1610 @@ +/* $Id: downmix.c,v 1.15 2005/03/17 19:22:47 stebbins Exp $ + + This file is part of the HandBrake source code. + Homepage: . + It may be used under the terms of the GNU General Public License. */ + +#include +#include +#include +#include "common.h" +#include "downmix.h" +#import +#import + +#define LVL_PLUS6DB 2.0 +#define LVL_PLUS3DB 1.4142135623730951 +#define LVL_3DB 0.7071067811865476 +#define LVL_45DB 0.5946035575013605 +#define LVL_6DB 0.5 + +#define LVL_SQRT_1_4 0.5 +#define LVL_SQRT_3_4 0.866025404 + +#define HB_CH_FRONT_LEFT 0x00000001 +#define HB_CH_FRONT_RIGHT 0x00000002 +#define HB_CH_FRONT_CENTER 0x00000004 +#define HB_CH_LOW_FREQUENCY 0x00000008 +#define HB_CH_BACK_LEFT 0x00000010 +#define HB_CH_BACK_RIGHT 0x00000020 +#define HB_CH_BACK_CENTER 0x00000040 +#define HB_CH_SIDE_LEFT 0x00000080 +#define HB_CH_SIDE_RIGHT 0x00000100 + +#define HB_CH_SURROUND_MASK 0x000001f0 +#define HB_CH_MASK 0x000007ff + +#define HB_CH_DOLBY 0x00000800 +#define HB_CH_DPLII 0x00001000 + +#define DOWNMIX_MONO 0 +#define DOWNMIX_STEREO 1 +#define DOWNMIX_3F 2 +#define DOWNMIX_2F1R 3 +#define DOWNMIX_3F1R 4 +#define DOWNMIX_2F2R 5 +#define DOWNMIX_3F2R 6 +#define DOWNMIX_3F4R 7 +#define DOWNMIX_DOLBY 8 +#define DOWNMIX_DPLII 9 +#define DOWNMIX_NUM_MODES 10 + +#define DOWNMIX_CHANNEL_MASK 0x0f + +#define DOWNMIX_LFE_FLAG 0x10 +#define DOWNMIX_FLAGS_MASK 0x10 + +hb_sample_t downmix_matrix[DOWNMIX_NUM_MODES][DOWNMIX_NUM_MODES][8][8] = +{ +// MONO in +{ + // MONO out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // STEREO out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F out + { { 0, LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F1R out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F1R out + { { 0, LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F2R out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F2R out + { { 0, LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F4R out + { { 0, LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DOLBY out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DPLII out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, +}, +// STEREO in +{ + // MONO out + { { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // STEREO out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F1R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F1R out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F2R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F2R out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F4R out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DOLBY out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DPLII out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, +}, +// 3F in +{ + // MONO out + { { LVL_PLUS3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // STEREO out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F1R out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F1R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F2R out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F2R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F4R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DOLBY out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DPLII out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, +}, +// 2F1R in +{ + // MONO out + { { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // STEREO out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F1R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F1R out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F2R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_3DB, LVL_3DB, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F2R out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_3DB, LVL_3DB, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F4R out + { { 0, 1, 0, 0, 0, 0, 0 , 0 }, + { 0, 0, 1, 0, 0, 0, 0 , 0 }, + { 0, 0, 0, 0, 0, LVL_3DB, LVL_3DB, 0 }, + { 0, 0, 0, 0, 0, 0, 0 , 1 }, + { 0, 0, 0, 0, 0, 0, 0 , 0 }, + { 0, 0, 0, 0, 0, 0, 0 , 0 }, + { 0, 0, 0, 0, 0, 0, 0 , 0 }, + { 0, 0, 0, 0, 0, 0, 0 , 0 } }, + // DOLBY out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { -LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DPLII out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { -LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, +}, +// 3F1R in +{ + // MONO out + { { LVL_PLUS3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // STEREO out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F1R out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F1R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F2R out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_3DB, LVL_3DB, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F2R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_3DB, LVL_3DB, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F4R out + { { 1, 0, 0, 0, 0, 0, 0 , 0 }, + { 0, 1, 0, 0, 0, 0, 0 , 0 }, + { 0, 0, 1, 0, 0, 0, 0 , 0 }, + { 0, 0, 0, 0, 0, LVL_3DB, LVL_3DB, 0 }, + { 0, 0, 0, 0, 0, 0, 0 , 1 }, + { 0, 0, 0, 0, 0, 0, 0 , 0 }, + { 0, 0, 0, 0, 0, 0, 0 , 0 }, + { 0, 0, 0, 0, 0, 0, 0 , 0 } }, + // DOLBY out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { -LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DPLII out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { -LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, +}, +// 2F2R in +{ + // MONO out + { { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // STEREO out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F1R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F1R out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_3DB, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_3DB, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F2R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F2R out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F4R out + { { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 1, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DOLBY out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { -LVL_6DB, LVL_6DB, 0, 0, 0, 0, 0, 0 }, + { -LVL_6DB, LVL_6DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DPLII out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { -LVL_SQRT_3_4, LVL_SQRT_1_4, 0, 0, 0, 0, 0, 0 }, + { -LVL_SQRT_1_4, LVL_SQRT_3_4, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, +}, +// 3F2R in +{ + // MONO out + { { LVL_PLUS3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // STEREO out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F1R out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F1R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_3DB, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_3DB, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 2F2R out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F2R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // 3F4R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 1, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DOLBY out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { -LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { -LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, + // DPLII out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { -LVL_SQRT_3_4, LVL_SQRT_1_4, 0, 0, 0, 0, 0, 0 }, + { -LVL_SQRT_1_4, LVL_SQRT_3_4, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }, +}, +// 3F4R in +{ + // MONO out + { { LVL_PLUS3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_6DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_6DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_6DB, 0, 0, 0, 0, 0, 0, 0 }, + { LVL_6DB, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 } }, + // STEREO out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { 0, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { LVL_3DB, 0, 0, 0, 0, 0, 0, 0 }, + { 0, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 } }, + // 3F out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 } }, + // 2F1R out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_6DB, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_6DB, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_6DB, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_6DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 } }, + // 3F1R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_6DB, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_6DB, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_6DB, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_6DB, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 } }, + // 2F2R out + { { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_3DB, 0, 0, 0, 0 }, + { 0, 0, LVL_3DB, 0, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_3DB, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 } }, + // 3F2R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, LVL_3DB, 0, 0, 0, 0 }, + { 0, 0, 0, 0, LVL_3DB, 0, 0, 0 }, + { 0, 0, 0, LVL_3DB, 0, 0, 0, 0 }, + { 0, 0, 0, 0, LVL_3DB, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 } }, + // 3F4R out + { { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 1, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 1 } }, + // DOLBY out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { -LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { -LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { -LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { -LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 } }, + // DPLII out + { { LVL_3DB, LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0, 0, 0 }, + { -LVL_SQRT_3_4*LVL_3DB, LVL_SQRT_1_4*LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { -LVL_SQRT_1_4*LVL_3DB, LVL_SQRT_3_4*LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { -LVL_SQRT_3_4*LVL_3DB, LVL_SQRT_1_4*LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { -LVL_SQRT_1_4*LVL_3DB, LVL_SQRT_3_4*LVL_3DB, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 } } +}, +}; + +static int channel_layout_map[DOWNMIX_NUM_MODES] = +{ + // DOWNMIX_MONO + (HB_CH_FRONT_CENTER), + // DOWNMIX_STEREO + (HB_CH_FRONT_LEFT|HB_CH_FRONT_RIGHT), + // DOWNMIX_3F + (HB_CH_FRONT_LEFT|HB_CH_FRONT_RIGHT|HB_CH_FRONT_CENTER), + // DOWNMIX_2F1R + (HB_CH_FRONT_LEFT|HB_CH_FRONT_RIGHT|HB_CH_BACK_CENTER), + // DOWNMIX_3F1R + (HB_CH_FRONT_LEFT|HB_CH_FRONT_RIGHT|HB_CH_FRONT_CENTER|HB_CH_BACK_CENTER), + // DOWNMIX_2F2R + (HB_CH_FRONT_LEFT|HB_CH_FRONT_RIGHT|HB_CH_BACK_LEFT|HB_CH_BACK_RIGHT), + // DOWNMIX_3F2R + (HB_CH_FRONT_LEFT|HB_CH_FRONT_RIGHT|HB_CH_FRONT_CENTER|HB_CH_BACK_LEFT|HB_CH_BACK_RIGHT), + // DOWNMIX_3F4R + (HB_CH_FRONT_LEFT|HB_CH_FRONT_RIGHT|HB_CH_FRONT_CENTER|HB_CH_SIDE_LEFT| + HB_CH_SIDE_RIGHT|HB_CH_BACK_LEFT|HB_CH_BACK_RIGHT), + // DOWNMIX_DOLBY + (HB_CH_FRONT_LEFT|HB_CH_FRONT_RIGHT), + // DOWNMIX_DPLII + (HB_CH_FRONT_LEFT|HB_CH_FRONT_RIGHT) +}; + +int hb_layout_to_mode(int layout) +{ + int mode; + switch (layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK) + { + case HB_INPUT_CH_LAYOUT_MONO: + mode = DOWNMIX_MONO; + break; + case HB_INPUT_CH_LAYOUT_STEREO: + mode = DOWNMIX_STEREO; + break; + case HB_INPUT_CH_LAYOUT_3F: + mode = DOWNMIX_3F; + break; + case HB_INPUT_CH_LAYOUT_2F1R: + mode = DOWNMIX_2F1R; + break; + case HB_INPUT_CH_LAYOUT_3F1R: + mode = DOWNMIX_3F1R; + break; + case HB_INPUT_CH_LAYOUT_2F2R: + mode = DOWNMIX_2F2R; + break; + case HB_INPUT_CH_LAYOUT_3F2R: + mode = DOWNMIX_3F2R; + break; + case HB_INPUT_CH_LAYOUT_4F2R: + mode = DOWNMIX_3F2R|DOWNMIX_LFE_FLAG; + break; + case HB_INPUT_CH_LAYOUT_3F4R: + mode = DOWNMIX_3F4R; + break; + case HB_INPUT_CH_LAYOUT_DOLBY: + mode = DOWNMIX_STEREO; + break; + default: + mode = DOWNMIX_STEREO; + break; + } + if (layout & HB_INPUT_CH_LAYOUT_DISCRETE_LFE_MASK) + mode |= DOWNMIX_LFE_FLAG; + return mode; +} + +int hb_mixdown_to_mode(uint32_t mixdown) +{ + switch (mixdown) + { + case HB_AMIXDOWN_MONO: + return DOWNMIX_MONO; + case HB_AMIXDOWN_STEREO: + return DOWNMIX_STEREO; + case HB_AMIXDOWN_DOLBY: + return DOWNMIX_DOLBY; + case HB_AMIXDOWN_DOLBYPLII: + return DOWNMIX_DPLII; + case HB_AMIXDOWN_6CH: + return DOWNMIX_3F2R|DOWNMIX_LFE_FLAG; + default: + return DOWNMIX_STEREO; + } +} + + +// ffmpeg gives us SMPTE channel layout +// We could use this layout and remap channels in encfaac, +// but VLC may have problems with remapping, so lets +// allow remapping to the default QuickTime order which is: +// +// C L R LS RS Rls Rrs LFE +// +// This arrangement also makes it possible to use half as +// many downmix matrices since the matrix with and without +// LFE are the same. +// +// Use hb_layout_remap to accomplish this. For convenience +// I've provided the necessary maps. +// +// SMPTE channel layout +// +// DUAL-MONO L R +// DUAL-MONO-LFE L R LFE +// MONO M +// MONO-LFE M LFE +// STEREO L R +// STEREO-LFE L R LFE +// 3F L R C +// 3F-LFE L R C LFE +// 2F1 L R S +// 2F1-LFE L R LFE S +// 3F1 L R C S +// 3F1-LFE L R C LFE S +// 2F2 L R LS RS +// 2F2-LFE L R LFE LS RS +// 3F2 L R C LS RS +// 3F2-LFE L R C LFE LS RS +// 3F4 L R C Rls Rrs LS RS +// 3F4-LFE L R C LFE Rls Rrs LS RS +// + +#define CH_C 0 +#define CH_L 1 +#define CH_R 2 +#define CH_CS 3 +#define CH_LS 3 +#define CH_RS 4 +#define CH_Rls 5 +#define CH_Rrs 6 +#define CH_LFE 7 + +hb_chan_map_t hb_qt_chan_map = +{ +{ + {{ CH_C, }, + { CH_C, CH_LFE, }}, // MONO + + {{ CH_L, CH_R, }, + { CH_L, CH_R, CH_LFE, }}, // STEREO + + {{ CH_C, CH_L, CH_R, }, + { CH_C, CH_L, CH_R, CH_LFE, }}, // 3F + + {{ CH_L, CH_R, CH_CS, }, + { CH_L, CH_R, CH_CS, CH_LFE, }}, // 2F1R + + {{ CH_C, CH_L, CH_R, CH_CS, }, + { CH_C, CH_L, CH_R, CH_CS, CH_LFE, }}, // 3F1R + + {{ CH_L, CH_R, CH_LS, CH_RS, }, + { CH_L, CH_R, CH_LS, CH_RS, CH_LFE, }}, // 2F2R + + {{ CH_C, CH_L, CH_R, CH_LS, CH_RS, }, + { CH_C, CH_L, CH_R, CH_LS, CH_RS, CH_LFE, }}, // 3F2R + + {{ CH_C, CH_L, CH_R, CH_LS, CH_RS, CH_Rls, CH_Rrs, }, + { CH_C, CH_L, CH_R, CH_LS, CH_RS, CH_Rls, CH_Rrs, CH_LFE }}, // 3F4R + + {{ CH_L, CH_R, }, + { CH_L, CH_R, }}, // DOLBY + + {{ CH_L, CH_R, }, + { CH_L, CH_R, }} // DPLII +}, +{ + // CH_C CH_L CH_R CH_LS/CS CH_RS CH_Rls CH_Rrs CH_LFE + {{ 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 1 }}, // MONO + + {{ 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 2 }}, // STEREO + + {{ 0, 1, 2, 0, 0, 0, 0, 0 }, + { 0, 1, 2, 0, 0, 0, 0, 3 }}, // 3F + + {{ 0, 0, 1, 2, 0, 0, 0, 0 }, + { 0, 0, 1, 2, 0, 0, 0, 3 }}, // 2F1R + + {{ 0, 1, 2, 3, 0, 0, 0, 0 }, + { 0, 1, 2, 3, 0, 0, 0, 4 }}, // 3F1R + + {{ 0, 0, 1, 2, 3, 0, 0, 0 }, + { 0, 0, 1, 2, 3, 0, 0, 4 }}, // 2F2R + + {{ 0, 1, 2, 3, 4, 0, 0, 0 }, + { 0, 1, 2, 3, 4, 0, 0, 5 }}, // 3F2R + + {{ 0, 1, 2, 3, 4, 5, 6, 0 }, + { 0, 1, 2, 3, 4, 5, 6, 7 }}, // 3F4R + + {{ 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }}, // DOLBY + + {{ 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }} // DPLII +} +}; + +hb_chan_map_t hb_smpte_chan_map = +{ +{ + {{ CH_C, }, + { CH_C, CH_LFE, }}, // MONO + + {{ CH_L, CH_R, }, + { CH_L, CH_R, CH_LFE, }}, // STEREO + + {{ CH_L, CH_R, CH_C, }, + { CH_L, CH_R, CH_C, CH_LFE, }}, // 3F + + {{ CH_L, CH_R, CH_CS, }, + { CH_L, CH_R, CH_LFE, CH_CS, }}, // 2F1R + + {{ CH_L, CH_R, CH_C, CH_CS, }, + { CH_L, CH_R, CH_LFE, CH_CS, }}, // 3F1R + + {{ CH_L, CH_R, CH_LS, CH_RS, }, + { CH_L, CH_R, CH_LFE, CH_LS, CH_RS, }}, // 2F2R + + {{ CH_L, CH_R, CH_C, CH_LS, CH_RS, }, + { CH_L, CH_R, CH_C, CH_LFE, CH_LS, CH_RS, }}, // 3F2R + + {{ CH_L, CH_R, CH_C, CH_Rls, CH_Rrs, CH_LS, CH_RS }, + { CH_L, CH_R, CH_C, CH_LFE, CH_Rls, CH_Rrs, CH_LS, CH_RS }}, // 3F4R + + {{ CH_L, CH_R, }, + { CH_L, CH_R, }}, // DOLBY + + {{ CH_L, CH_R, }, + { CH_L, CH_R, }} // DPLII +}, +{ + // CH_C CH_L CH_R CH_LS/CS CH_RS CH_Rls CH_Rrs CH_LFE + {{ 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 1 }}, // MONO + + {{ 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 2 }}, // STEREO + + {{ 2, 0, 1, 0, 0, 0, 0, 0 }, + { 2, 0, 1, 0, 0, 0, 0, 3 }}, // 3F + + {{ 0, 0, 1, 2, 0, 0, 0, 0 }, + { 0, 0, 1, 3, 0, 0, 0, 2 }}, // 2F1R + + {{ 2, 0, 1, 3, 0, 0, 0, 0 }, + { 2, 0, 1, 4, 0, 0, 0, 3 }}, // 3F1R + + {{ 0, 0, 1, 2, 3, 0, 0, 0 }, + { 0, 0, 1, 3, 4, 0, 0, 2 }}, // 2F2R + + {{ 2, 0, 1, 3, 4, 0, 0, 0 }, + { 2, 0, 1, 4, 5, 0, 0, 3 }}, // 3F2R + + {{ 2, 0, 1, 5, 6, 3, 4, 0 }, + { 2, 0, 1, 6, 7, 4, 5, 3 }}, // 3F4R + + {{ 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }}, // DOLBY + + {{ 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }} // DPLII +} +}; + +hb_chan_map_t hb_ac3_chan_map = +{ +{ + {{ CH_C, }, + { CH_LFE, CH_C, }}, // MONO + + {{ CH_L, CH_R, }, + { CH_LFE, CH_L, CH_R, }}, // STEREO + + {{ CH_L, CH_C, CH_R, }, + { CH_LFE, CH_L, CH_C, CH_R, }}, // 3F + + {{ CH_L, CH_R, CH_CS, }, + { CH_LFE, CH_L, CH_R, CH_CS, }}, // 2F1R + + {{ CH_L, CH_C, CH_R, CH_CS, }, + { CH_LFE, CH_L, CH_C, CH_R, CH_CS, }}, // 3F1R + + {{ CH_L, CH_R, CH_LS, CH_RS, }, + { CH_LFE, CH_L, CH_R, CH_LS, CH_RS, }}, // 2F2R + + {{ CH_L, CH_C, CH_R, CH_LS, CH_RS, }, + { CH_LFE, CH_L, CH_C, CH_R, CH_LS, CH_RS, }}, // 3F2R + + {{ CH_L, CH_C, CH_R, CH_LS, CH_RS, CH_Rls, CH_Rrs, }, + { CH_LFE, CH_L, CH_C, CH_R, CH_LS, CH_RS, CH_Rls, CH_Rrs }}, // 3F4R + + {{ CH_L, CH_R, }, + { CH_L, CH_R, }}, // DOLBY + + {{ CH_L, CH_R, }, + { CH_L, CH_R, }} // DPLII +}, +{ + // CH_C CH_L CH_R CH_LS/CS CH_RS CH_Rls CH_Rrs CH_LFE + {{ 0, 0, 0, 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0 }}, // MONO + + {{ 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 1, 2, 0, 0, 0, 0, 0 }}, // STEREO + + {{ 1, 0, 2, 0, 0, 0, 0, 0 }, + { 2, 1, 3, 0, 0, 0, 0, 0 }}, // 3F + + {{ 0, 0, 1, 2, 0, 0, 0, 0 }, + { 0, 1, 2, 3, 0, 0, 0, 0 }}, // 2F1R + + {{ 1, 0, 2, 3, 0, 0, 0, 0 }, + { 2, 1, 3, 4, 0, 0, 0, 0 }}, // 3F1R + + {{ 0, 0, 1, 2, 3, 0, 0, 0 }, + { 0, 1, 2, 3, 4, 0, 0, 0 }}, // 2F2R + + {{ 1, 0, 2, 3, 4, 0, 0, 0 }, + { 2, 1, 3, 4, 5, 0, 0, 0 }}, // 3F2R + + {{ 1, 0, 2, 3, 4, 5, 6, 0 }, + { 2, 1, 3, 4, 5, 6, 7, 0 }}, // 3F4R + + {{ 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }}, // DOLBY + + {{ 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 0, 0, 0, 0, 0 }} // DPLII +} +}; + +static const uint8_t nchans_tbl[] = {1, 2, 3, 3, 4, 4, 5, 7, 2, 2}; + +// Takes a set of samples and remaps the channel layout +void hb_layout_remap( + hb_chan_map_t * map_in, + hb_chan_map_t * map_out, + int layout, + hb_sample_t * samples, + int nsamples ) +{ + int nchans; + int ii, jj; + int lfe; + int * map; + int * inv_map; + int mode; + hb_sample_t tmp[8]; + + mode = hb_layout_to_mode(layout); + lfe = ((mode & DOWNMIX_LFE_FLAG) != 0); + mode = mode & DOWNMIX_CHANNEL_MASK; + nchans = nchans_tbl[mode] + lfe; + inv_map = map_in->inv_chan_map[mode][lfe]; + map = map_out->chan_map[mode][lfe]; + + for (ii = 0; ii < nsamples; ii++) + { + for (jj = 0; jj < nchans; jj++) + { + tmp[jj] = samples[jj]; + } + for (jj = 0; jj < nchans; jj++) + { + int ord = map[jj]; + samples[jj] = tmp[inv_map[ord]]; + } + samples += nchans; + } +} + +static void matrix_mul( + hb_sample_t * dst, + hb_sample_t * src, + int nchans_out, + int nchans_in, + int nsamples, + hb_sample_t (*matrix)[8], + hb_sample_t bias) +{ + int nn, ii, jj; + hb_sample_t val; + + for (nn = 0; nn < nsamples; nn++) + { + for (ii = 0; ii < nchans_out; ii++) + { + val = 0; + for (jj = 0; jj < nchans_in; jj++) + { + val += src[jj] * matrix[jj][ii]; + } + dst[ii] = val + bias; + } + src += nchans_in; + dst += nchans_out; + } +} + +static void set_level( hb_downmix_t * downmix ) +{ + int ii, jj; + int layout_in, layout_out; + int mode_in; + int mode_out; + + mode_in = downmix->mode_in & ~DOWNMIX_FLAGS_MASK; + mode_out = downmix->mode_out & ~DOWNMIX_FLAGS_MASK; + + for (ii = 0; ii < 8; ii++) + { + for (jj = 0; jj < 8; jj++) + { + downmix->matrix[ii][jj] *= downmix->level; + } + } + if (mode_out >= DOWNMIX_DOLBY) + return; + + layout_in = channel_layout_map[mode_in]; + layout_out = channel_layout_map[mode_out]; + + if (layout_in & HB_CH_FRONT_CENTER) + { + if (!(layout_out & HB_CH_FRONT_CENTER)) + { + for (jj = 0; jj < 8; jj++) + { + downmix->matrix[downmix->center][jj] *= downmix->clev; + } + } + } + if (layout_in & (HB_CH_BACK_LEFT|HB_CH_BACK_RIGHT|HB_CH_BACK_CENTER|HB_CH_SIDE_LEFT|HB_CH_SIDE_RIGHT)) + { + if (layout_out & (HB_CH_BACK_LEFT|HB_CH_BACK_RIGHT|HB_CH_BACK_CENTER|HB_CH_SIDE_LEFT|HB_CH_SIDE_RIGHT)) + { + // Note, slev only gets set if input has surround, and output has none. + return; + } + } + for (jj = 0; jj < 8; jj++) + { + if ( downmix->left_surround >= 0 ) + downmix->matrix[downmix->left_surround][jj] *= downmix->slev; + if ( downmix->right_surround >= 0 ) + downmix->matrix[downmix->right_surround][jj] *= downmix->slev; + if ( downmix->rear_left_surround >= 0 ) + downmix->matrix[downmix->rear_left_surround][jj] *= downmix->slev; + if ( downmix->rear_right_surround >= 0 ) + downmix->matrix[downmix->rear_right_surround][jj] *= downmix->slev; + } +} + +#define MIXMODE(x,y) (((x)<<4)|(y)) +// The downmix operation can result in new sample values that are +// outside the original range of sample values. If you wish to +// guarantee that the levels to not exceed the original range, +// call this function after initializing downmix and setting +// your initial levels. +// +// Note that this can result in generally lower volume levels +// in the resulting downmixed audio. +void hb_downmix_adjust_level( hb_downmix_t * downmix ) +{ + int mode_in, mode_out; + hb_sample_t level = downmix->level; + hb_sample_t clev = downmix->clev; + hb_sample_t slev = downmix->slev; + + mode_in = downmix->mode_in & DOWNMIX_CHANNEL_MASK; + mode_out = downmix->mode_out & DOWNMIX_CHANNEL_MASK; + + switch MIXMODE(mode_in, mode_out) + { + case MIXMODE(DOWNMIX_STEREO, DOWNMIX_MONO): + case MIXMODE(DOWNMIX_2F2R, DOWNMIX_2F1R): + case MIXMODE(DOWNMIX_2F2R, DOWNMIX_3F1R): + case MIXMODE(DOWNMIX_3F2R, DOWNMIX_3F1R): + case MIXMODE(DOWNMIX_3F4R, DOWNMIX_3F1R): + case MIXMODE(DOWNMIX_3F4R, DOWNMIX_3F2R): + level_3db: + level /= LVL_PLUS3DB; + break; + + case MIXMODE(DOWNMIX_3F, DOWNMIX_MONO): + level /= LVL_PLUS3DB + clev * LVL_PLUS3DB; + break; + + case MIXMODE(DOWNMIX_3F2R, DOWNMIX_2F1R): + case MIXMODE(DOWNMIX_3F4R, DOWNMIX_2F1R): + case MIXMODE(DOWNMIX_3F4R, DOWNMIX_2F2R): + if (1 + clev < LVL_PLUS3DB) + goto level_3db; + case MIXMODE(DOWNMIX_3F, DOWNMIX_STEREO): + case MIXMODE(DOWNMIX_3F, DOWNMIX_2F1R): + case MIXMODE(DOWNMIX_3F, DOWNMIX_2F2R): + case MIXMODE(DOWNMIX_3F, DOWNMIX_DOLBY): + case MIXMODE(DOWNMIX_3F, DOWNMIX_DPLII): + case MIXMODE(DOWNMIX_3F1R, DOWNMIX_2F1R): + case MIXMODE(DOWNMIX_3F1R, DOWNMIX_2F2R): + case MIXMODE(DOWNMIX_3F2R, DOWNMIX_2F2R): + level /= 1 + clev; + break; + + + case MIXMODE(DOWNMIX_2F1R, DOWNMIX_MONO): + level /= LVL_PLUS3DB + LVL_3DB * clev; + break; + + case MIXMODE(DOWNMIX_2F1R, DOWNMIX_DOLBY): + level /= 1 + LVL_3DB; + break; + + case MIXMODE(DOWNMIX_2F1R, DOWNMIX_STEREO): + case MIXMODE(DOWNMIX_2F1R, DOWNMIX_3F): + case MIXMODE(DOWNMIX_3F1R, DOWNMIX_3F): + level /= 1 + LVL_3DB * slev; + break; + + case MIXMODE(DOWNMIX_3F1R, DOWNMIX_MONO): + level /= LVL_PLUS3DB + LVL_PLUS3DB * clev + LVL_3DB * slev; + break; + + case MIXMODE(DOWNMIX_3F1R, DOWNMIX_STEREO): + level /= 1 + clev + LVL_3DB * slev; + break; + + case MIXMODE(DOWNMIX_3F1R, DOWNMIX_DOLBY): + case MIXMODE(DOWNMIX_3F1R, DOWNMIX_DPLII): + case MIXMODE(DOWNMIX_2F2R, DOWNMIX_DOLBY): + level /= 1 + LVL_PLUS3DB; + break; + + case MIXMODE(DOWNMIX_2F2R, DOWNMIX_MONO): + level /= LVL_PLUS3DB + LVL_PLUS3DB * slev; + break; + + case MIXMODE(DOWNMIX_2F2R, DOWNMIX_STEREO): + case MIXMODE(DOWNMIX_2F2R, DOWNMIX_3F): + case MIXMODE(DOWNMIX_3F2R, DOWNMIX_3F): + level /= 1 + slev; + break; + + case MIXMODE(DOWNMIX_2F2R, DOWNMIX_DPLII): + level /= 1 + LVL_SQRT_1_4 + LVL_SQRT_3_4; + break; + + case MIXMODE(DOWNMIX_3F2R, DOWNMIX_MONO): + case MIXMODE(DOWNMIX_3F4R, DOWNMIX_MONO): + level /= LVL_PLUS3DB + LVL_PLUS3DB * clev * LVL_PLUS3DB * slev; + break; + + case MIXMODE(DOWNMIX_3F2R, DOWNMIX_STEREO): + level /= 1 + clev + slev; + break; + + case MIXMODE(DOWNMIX_3F2R, DOWNMIX_DOLBY): + level /= 1 + 3 * LVL_3DB; + break; + + case MIXMODE(DOWNMIX_3F2R, DOWNMIX_DPLII): + level /= 1 + LVL_3DB + LVL_SQRT_1_4 + LVL_SQRT_3_4; + break; + + case MIXMODE(DOWNMIX_3F4R, DOWNMIX_STEREO): + level /= 1 + clev + LVL_PLUS3DB * slev; + break; + + case MIXMODE(DOWNMIX_3F4R, DOWNMIX_3F): + level /= 1 + LVL_PLUS3DB * slev; + break; + + case MIXMODE(DOWNMIX_3F4R, DOWNMIX_DOLBY): + level /= 1 + 5 * LVL_3DB; + break; + + case MIXMODE(DOWNMIX_3F4R, DOWNMIX_DPLII): + level /= 1 + LVL_3DB + 2 * LVL_SQRT_1_4 + 2 * LVL_SQRT_3_4; + } + + downmix->level = level; + downmix->matrix_initialized = 0; +} + +void hb_downmix_set_bias( hb_downmix_t * downmix, hb_sample_t bias ) +{ + downmix->bias = bias; +} + +// Changes the downmix mode if it needs changing after initialization +static void set_mode( hb_downmix_t * downmix ) +{ + int ii, jj; + int mode_in, mode_out; + hb_sample_t (*matrix)[8]; + + mode_in = downmix->mode_in & ~DOWNMIX_FLAGS_MASK; + mode_out = downmix->mode_out & ~DOWNMIX_FLAGS_MASK; + + matrix = downmix_matrix[mode_in][mode_out]; + + for (ii = 0; ii < 8; ii++) + { + for (jj = 0; jj < 8; jj++) + { + downmix->matrix[ii][jj] = matrix[ii][jj]; + } + } +} + +// Changes the downmix mode if it needs changing after initialization +int hb_downmix_set_mode( hb_downmix_t * downmix, int layout, int mixdown ) +{ + int lfe_in, lfe_out; + int mode_in, mode_out; + + if ( downmix == NULL ) + return -1; + + mode_in = hb_layout_to_mode(layout); + mode_out = hb_mixdown_to_mode(mixdown); + downmix->mode_in = mode_in; + downmix->mode_out = mode_out; + + mode_in = downmix->mode_in & ~DOWNMIX_FLAGS_MASK; + mode_out = downmix->mode_out & ~DOWNMIX_FLAGS_MASK; + + if (mode_in >= DOWNMIX_NUM_MODES || mode_out >= DOWNMIX_NUM_MODES) + return -1; + + lfe_in = ((downmix->mode_in & DOWNMIX_LFE_FLAG) != 0); + lfe_out = ((downmix->mode_out & DOWNMIX_LFE_FLAG) != 0); + + downmix->nchans_in = nchans_tbl[mode_in] + lfe_in; + downmix->nchans_out = nchans_tbl[mode_out] + lfe_out; + + downmix->matrix_initialized = 0; + return 0; +} + +// Changes the downmix levels if they need changing after initialization +void hb_downmix_set_level( hb_downmix_t * downmix, hb_sample_t clev, hb_sample_t slev, hb_sample_t level ) +{ + if ( downmix == NULL ) + return; + + downmix->clev = clev; + downmix->slev = slev; + downmix->level = level; + downmix->matrix_initialized = 0; +} + +static void set_chan_map( hb_downmix_t * downmix ) +{ + int nchans; + int ii, jj; + int lfe; + int * map; + int * inv_map; + int mode; + hb_sample_t matrix[8][8]; + + // Copy the matrix + for ( ii = 0; ii < 8; ii++ ) + { + for ( jj = 0; jj < 8; jj++ ) + { + matrix[ii][jj] = downmix->matrix[ii][jj]; + } + } + + // Rearrange the rows to correspond to the input channel order + lfe = ((downmix->mode_in & DOWNMIX_LFE_FLAG) != 0); + mode = downmix->mode_in & DOWNMIX_CHANNEL_MASK; + nchans = nchans_tbl[mode] + lfe; + map = downmix->map_in.chan_map[mode][lfe]; + inv_map = hb_qt_chan_map.inv_chan_map[mode][lfe]; + + downmix->center = -1; + downmix->left_surround = -1; + downmix->right_surround = -1; + downmix->rear_left_surround = -1; + downmix->rear_right_surround = -1; + for ( ii = 0; ii < nchans; ii++ ) + { + int ord = map[ii]; + int row = inv_map[ord]; + switch (ord) + { + case CH_C: + downmix->center = ii; + break; + case CH_LS: + downmix->left_surround = ii; + break; + case CH_RS: + downmix->right_surround = ii; + break; + case CH_Rls: + downmix->rear_right_surround = ii; + break; + case CH_Rrs: + downmix->rear_left_surround = ii; + break; + } + for ( jj = 0; jj < 8; jj++ ) + { + downmix->matrix[ii][jj] = matrix[row][jj]; + } + } + + // Copy the matrix + for ( ii = 0; ii < 8; ii++ ) + { + for ( jj = 0; jj < 8; jj++ ) + { + matrix[ii][jj] = downmix->matrix[ii][jj]; + } + } + + // Rearrange the columns to correspond to the output channel order + lfe = ((downmix->mode_out & DOWNMIX_LFE_FLAG) != 0); + mode = downmix->mode_out & DOWNMIX_CHANNEL_MASK; + nchans = nchans_tbl[mode] + lfe; + map = downmix->map_out.chan_map[mode][lfe]; + inv_map = hb_qt_chan_map.inv_chan_map[mode][lfe]; + for ( ii = 0; ii < nchans; ii++ ) + { + int ord = map[ii]; + int col = inv_map[ord]; + for ( jj = 0; jj < 8; jj++ ) + { + downmix->matrix[jj][ii] = matrix[jj][col]; + } + } +} + +void hb_downmix_set_chan_map( + hb_downmix_t * downmix, + hb_chan_map_t * map_in, + hb_chan_map_t * map_out ) +{ + downmix->map_in = *map_in; + downmix->map_out = *map_out; + downmix->matrix_initialized = 0; +} + +hb_downmix_t * hb_downmix_init(int layout, int mixdown) +{ + hb_downmix_t * downmix = calloc(1, sizeof(hb_downmix_t)); + + if (downmix == NULL) + return NULL; + if ( hb_downmix_set_mode( downmix, layout, mixdown ) < 0 ) + { + free( downmix ); + return NULL; + } + // Set some good default values + hb_downmix_set_level( downmix, LVL_3DB, LVL_3DB, 1.0 ); + downmix->bias = 0.0; + downmix->matrix_initialized = 0; + // The default input and output channel order is QT + hb_downmix_set_chan_map( downmix, &hb_qt_chan_map, &hb_qt_chan_map ); + return downmix; +} + +void hb_downmix_close( hb_downmix_t **downmix ) +{ + if (*downmix != NULL) + free(*downmix); + *downmix = NULL; +} + +static void init_matrix( hb_downmix_t * downmix ) +{ + if ( !downmix->matrix_initialized ) + { + set_mode( downmix ); + set_chan_map( downmix ); + set_level(downmix); + downmix->matrix_initialized = 1; + } +} + +void hb_downmix( hb_downmix_t * downmix, hb_sample_t * dst, hb_sample_t * src, int nsamples) +{ + init_matrix( downmix ); + matrix_mul( dst, src, downmix->nchans_out, downmix->nchans_in, + nsamples, downmix->matrix, downmix->bias ); +} + +int hb_need_downmix( int layout, int mixdown ) +{ + int mode_in, mode_out; + + mode_in = hb_layout_to_mode(layout); + mode_out = hb_mixdown_to_mode(mixdown); + + return (mode_in != mode_out); +} diff --git a/MP42/muxer/downmix.h b/MP42/muxer/downmix.h new file mode 100644 index 0000000..8f87a67 --- /dev/null +++ b/MP42/muxer/downmix.h @@ -0,0 +1,108 @@ +/* $Id: downmix.h,v 1.51 2005/11/04 13:09:40 stebbins Exp $ + + This file is part of the HandBrake source code. + Homepage: . + It may be used under the terms of the GNU General Public License. */ + +#ifndef DOWNMIX_H +#define DOWNMIX_H + +/* Input Channel Layout */ +/* define some masks, used to extract the various information from the HB_AMIXDOWN_XXXX values */ +#define HB_INPUT_CH_LAYOUT_DISCRETE_FRONT_MASK 0x00F0000 +#define HB_INPUT_CH_LAYOUT_DISCRETE_REAR_MASK 0x000F000 +#define HB_INPUT_CH_LAYOUT_DISCRETE_LFE_MASK 0x0000F00 +#define HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK 0xFFFF0FF +#define HB_INPUT_CH_LAYOUT_ENCODED_FRONT_MASK 0x00000F0 +#define HB_INPUT_CH_LAYOUT_ENCODED_REAR_MASK 0x000000F +/* define the input channel layouts used to describe the channel layout of this audio */ +#define HB_INPUT_CH_LAYOUT_MONO 0x0110010 +#define HB_INPUT_CH_LAYOUT_STEREO 0x0220020 +#define HB_INPUT_CH_LAYOUT_DOLBY 0x0320031 +#define HB_INPUT_CH_LAYOUT_3F 0x0430030 +#define HB_INPUT_CH_LAYOUT_2F1R 0x0521021 +#define HB_INPUT_CH_LAYOUT_3F1R 0x0631031 +#define HB_INPUT_CH_LAYOUT_2F2R 0x0722022 +#define HB_INPUT_CH_LAYOUT_3F2R 0x0832032 +#define HB_INPUT_CH_LAYOUT_4F2R 0x0942042 +#define HB_INPUT_CH_LAYOUT_3F4R 0x0a34034 +#define HB_INPUT_CH_LAYOUT_HAS_LFE 0x0000100 + +#define HB_AMIXDOWN_MONO 0x01000001 +// DCA_FORMAT of DCA_MONO = 0 = 0x000 +// A52_FORMAT of A52_MONO = 1 = 0x01 +// discrete channel count of 1 +#define HB_AMIXDOWN_STEREO 0x02002022 +// DCA_FORMAT of DCA_STEREO = 2 = 0x002 +// A52_FORMAT of A52_STEREO = 2 = 0x02 +// discrete channel count of 2 +#define HB_AMIXDOWN_DOLBY 0x042070A2 +// DCA_FORMAT of DCA_3F1R | DCA_OUT_DPLI = 519 = 0x207 +// A52_FORMAT of A52_DOLBY = 10 = 0x0A +// discrete channel count of 2 +#define HB_AMIXDOWN_DOLBYPLII 0x084094A2 +// DCA_FORMAT of DCA_3F2R | DCA_OUT_DPLII = 1033 = 0x409 +// A52_FORMAT of A52_DOLBY | A52_USE_DPLII = 74 = 0x4A +// discrete channel count of 2 +#define HB_AMIXDOWN_6CH 0x10089176 +// DCA_FORMAT of DCA_3F2R | DCA_LFE = 137 = 0x089 +// A52_FORMAT of A52_3F2R | A52_LFE = 23 = 0x17 +// discrete channel count of 6 + +typedef float hb_sample_t; + +typedef struct +{ + int chan_map[10][2][8]; + int inv_chan_map[10][2][8]; +} hb_chan_map_t; + +typedef struct +{ + int mode_in; + int mode_out; + int nchans_in; + int nchans_out; + hb_sample_t matrix[8][8]; + int matrix_initialized; + hb_sample_t clev; + hb_sample_t slev; + hb_sample_t level; + hb_sample_t bias; + hb_chan_map_t map_in; + hb_chan_map_t map_out; + + int center; + int left_surround; + int right_surround; + int rear_left_surround; + int rear_right_surround; +} hb_downmix_t; + +// For convenience, a map to convert smpte channel layout +// to QuickTime channel layout. +// Map Indicies are mode, lfe, channel respectively +extern hb_chan_map_t hb_smpte_chan_map; +extern hb_chan_map_t hb_ac3_chan_map; +extern hb_chan_map_t hb_qt_chan_map; + +hb_downmix_t * hb_downmix_init(int layout, int mixdown); +void hb_downmix_close( hb_downmix_t **downmix ); +int hb_downmix_set_mode( hb_downmix_t * downmix, int layout, int mixdown ); +void hb_downmix_set_level( hb_downmix_t * downmix, hb_sample_t clev, hb_sample_t slev, hb_sample_t level ); +void hb_downmix_adjust_level( hb_downmix_t * downmix ); +void hb_downmix_set_bias( hb_downmix_t * downmix, hb_sample_t bias ); +void hb_downmix_set_chan_map( + hb_downmix_t * downmix, + hb_chan_map_t * map_in, + hb_chan_map_t * map_out ); +void hb_downmix( hb_downmix_t * downmix, hb_sample_t * dst, hb_sample_t * src, int nsamples); +void hb_layout_remap( + hb_chan_map_t * map_in, + hb_chan_map_t * map_out, + int layout, + hb_sample_t * samples, + int nsamples ); +int hb_need_downmix( int layout, int mixdown ); + +#endif /* DOWNMIX_H */ diff --git a/MP42/muxer/mbs.cpp b/MP42/muxer/mbs.cpp new file mode 100644 index 0000000..72df752 --- /dev/null +++ b/MP42/muxer/mbs.cpp @@ -0,0 +1,94 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is MPEG4IP. + * + * The Initial Developer of the Original Code is Cisco Systems Inc. + * Portions created by Cisco Systems Inc. are + * Copyright (C) Cisco Systems Inc. 2001-2002. All Rights Reserved. + * + * Contributor(s): + * Dave Mackie dmackie@cisco.com + */ + +#include "mbs.h" + +void CMemoryBitstream::AllocBytes(u_int32_t numBytes) +{ + m_pBuf = (u_int8_t*)calloc(numBytes, 1); + if (!m_pBuf) { + throw ENOMEM; + } + m_alloced = true; + m_bitPos = 0; + m_numBits = numBytes << 3; +} + +void CMemoryBitstream::SetBytes(u_int8_t* pBytes, u_int32_t numBytes) +{ + m_pBuf = pBytes; + m_bitPos = 0; + m_numBits = numBytes << 3; +} + +void CMemoryBitstream::PutBytes(u_int8_t* pBytes, u_int32_t numBytes) +{ + u_int32_t numBits = numBytes << 3; + + if (numBits + m_bitPos > m_numBits) { + throw EIO; + } + + if ((m_bitPos & 7) == 0) { + memcpy(&m_pBuf[m_bitPos >> 3], pBytes, numBytes); + m_bitPos += numBits; + } else { + for (u_int32_t i = 0; i < numBytes; i++) { + PutBits(pBytes[i], 8); + } + } +} + +void CMemoryBitstream::PutBits(u_int32_t bits, u_int32_t numBits) +{ + if (numBits + m_bitPos > m_numBits) { + throw EIO; + } + if (numBits > 32) { + throw EIO; + } + + for (int8_t i = numBits - 1; i >= 0; i--) { + m_pBuf[m_bitPos >> 3] |= ((bits >> i) & 1) << (7 - (m_bitPos & 7)); + m_bitPos++; + } +} + +u_int32_t CMemoryBitstream::GetBits(u_int32_t numBits) +{ + if (numBits + m_bitPos > m_numBits) { + throw EIO; + } + if (numBits > 32) { + throw EIO; + } + + u_int32_t bits = 0; + + for (u_int8_t i = 0; i < numBits; i++) { + bits <<= 1; + bits |= (m_pBuf[m_bitPos >> 3] >> (7 - (m_bitPos & 7))) & 1; + m_bitPos++; + } + + return bits; +} + diff --git a/MP42/muxer/mbs.h b/MP42/muxer/mbs.h new file mode 100644 index 0000000..617c528 --- /dev/null +++ b/MP42/muxer/mbs.h @@ -0,0 +1,96 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is MPEG4IP. + * + * The Initial Developer of the Original Code is Cisco Systems Inc. + * Portions created by Cisco Systems Inc. are + * Copyright (C) Cisco Systems Inc. 2001-2002. All Rights Reserved. + * + * Contributor(s): + * Dave Mackie dmackie@cisco.com + */ + +#include "mp4v2.h" +#include +#include /* isdigit, isprint, isspace */ +#include +#include +#include +#include +#include +#include + +#ifndef __MBS_INCLUDED__ +#define __MBS_INCLUDED__ + +class CMemoryBitstream { +public: + CMemoryBitstream() { + m_pBuf = NULL; + m_bitPos = 0; + m_numBits = 0; + m_alloced = false; + } + ~CMemoryBitstream(void) { + if (m_alloced) free(m_pBuf); + } + void AllocBytes(u_int32_t numBytes); + + void SetBytes(u_int8_t* pBytes, u_int32_t numBytes); + + void PutBytes(u_int8_t* pBytes, u_int32_t numBytes); + + void PutBits(u_int32_t bits, u_int32_t numBits); + + u_int32_t GetBits(u_int32_t numBits); + + void SkipBytes(u_int32_t numBytes) { + SkipBits(numBytes << 3); + } + + void SkipBits(u_int32_t numBits) { + SetBitPosition(GetBitPosition() + numBits); + } + + u_int32_t GetBitPosition() { + return m_bitPos; + } + + void SetBitPosition(u_int32_t bitPos) { + if (bitPos > m_numBits) { + throw; + } + m_bitPos = bitPos; + } + + u_int8_t* GetBuffer() { + m_alloced = false; + return m_pBuf; + } + + u_int32_t GetNumberOfBytes() { + return (GetNumberOfBits() + 7) / 8; + } + + u_int32_t GetNumberOfBits() { + return m_numBits; + } + +protected: + u_int8_t* m_pBuf; + u_int32_t m_bitPos; + u_int32_t m_numBits; + bool m_alloced; +}; + +#endif /* __MBS_INCLUDED__ */ + diff --git a/MP42/muxer/mpeg4ip_bitstream.h b/MP42/muxer/mpeg4ip_bitstream.h new file mode 100644 index 0000000..7911714 --- /dev/null +++ b/MP42/muxer/mpeg4ip_bitstream.h @@ -0,0 +1,207 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is MPEG4IP. + * + * The Initial Developer of the Original Code is Cisco Systems Inc. + * Portions created by Cisco Systems Inc. are + * Copyright (C) Cisco Systems Inc. 2001-2005. All Rights Reserved. + * + * Contributor(s): + * Bill May wmay@cisco.com + */ + +#ifndef __BITSTREAM_H__ +#define __BITSTREAM_H__ 1 +//#include "mpeg4ip.h" + +#ifndef MIN +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif + +typedef enum BitstreamErr_t { + BITSTREAM_TOO_MANY_BITS, + BITSTREAM_PAST_END, +} BitstreamErr_t; + +class CBitstream { + public: + CBitstream(void) { m_verbose = 0;}; + CBitstream(const uint8_t *buffer, uint32_t bit_len) { + m_verbose = 0; + init(buffer, bit_len); + }; + ~CBitstream (void) {}; + void init(const uint8_t *buffer, uint32_t bit_len) { + m_chDecBuffer = buffer; + m_chDecBufferSize = bit_len; + m_bBookmarkOn = 0; + m_uNumOfBitsInBuffer = 0; + + }; + void init(const char *buffer, uint32_t bit_len) { + init((const uint8_t *)buffer, (uint32_t)bit_len); + }; + void init(const char *buffer, int bit_len) { + init((const uint8_t *)buffer, (uint32_t)bit_len); + }; + void init(const uint8_t *buffer, int bit_len) { + init(buffer, (uint32_t)bit_len); + }; + void init(const char *buffer, unsigned short bit_len) { + init((const uint8_t *)buffer, (uint32_t)bit_len); + }; + void init(const uint8_t *buffer, unsigned short bit_len) { + init(buffer, (uint32_t)bit_len); + }; + uint32_t GetBits(uint32_t numBits) { + uint32_t retData; + static const uint32_t msk[33] = { + 0x00000000, 0x00000001, 0x00000003, 0x00000007, + 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, + 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, + 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, + 0x0000ffff, 0x0001ffff, 0x0003ffff, 0x0007ffff, + 0x000fffff, 0x001fffff, 0x003fffff, 0x007fffff, + 0x00ffffff, 0x01ffffff, 0x03ffffff, 0x07ffffff, + 0x0fffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff, + 0xffffffff + }; + + if (numBits > 32) { + throw BITSTREAM_TOO_MANY_BITS; + } + + if (numBits == 0) { + return 0; + } + + if (m_uNumOfBitsInBuffer >= numBits) { // don't need to read from FILE + m_uNumOfBitsInBuffer -= numBits; + retData = m_chDecData >> m_uNumOfBitsInBuffer; + // wmay - this gets done below...retData &= msk[numBits]; + } else { + uint32_t nbits; + nbits = numBits - m_uNumOfBitsInBuffer; + if (nbits == 32) + retData = 0; + else + retData = m_chDecData << nbits; + switch ((nbits - 1) / 8) { + case 3: + nbits -= 8; + if (m_chDecBufferSize < 8) throw BITSTREAM_PAST_END; + retData |= *m_chDecBuffer++ << nbits; + m_chDecBufferSize -= 8; + // fall through + case 2: + nbits -= 8; + if (m_chDecBufferSize < 8) throw BITSTREAM_PAST_END; + retData |= *m_chDecBuffer++ << nbits; + m_chDecBufferSize -= 8; + case 1: + nbits -= 8; + if (m_chDecBufferSize < 8) throw BITSTREAM_PAST_END; + retData |= *m_chDecBuffer++ << nbits; + m_chDecBufferSize -= 8; + case 0: + break; + } + if (m_chDecBufferSize < nbits) { + throw BITSTREAM_PAST_END; + } + m_chDecData = *m_chDecBuffer++; + m_uNumOfBitsInBuffer = MIN(8, m_chDecBufferSize) - nbits; + m_chDecBufferSize -= MIN(8, m_chDecBufferSize); + retData |= (m_chDecData >> m_uNumOfBitsInBuffer) & msk[nbits]; + } + if (m_verbose) + printf("bits %d value %x\n", numBits, retData&msk[numBits]); + return (retData & msk[numBits]); + }; + int getbits(uint32_t bits, uint32_t *retvalue) { + try { + *retvalue = GetBits(bits); + } catch (...) { + return -1; + } + return 0; + } + int peekbits(uint32_t bits, uint32_t *retvalue) { + int ret; + bookmark(1); + ret = getbits(bits, retvalue); + bookmark(0); + return (ret); + } + uint32_t PeekBits(uint32_t bits) { + uint32_t ret; + bookmark(1); + ret = GetBits(bits); + bookmark(0); + return ret; + } + void bookmark(int bSet) { + if (m_verbose) { + printf("bookmark\n"); + } + if (bSet) { + m_uNumOfBitsInBuffer_bookmark = m_uNumOfBitsInBuffer; + m_chDecBuffer_bookmark = m_chDecBuffer; + m_chDecBufferSize_bookmark = m_chDecBufferSize; + m_bBookmarkOn = 1; + m_chDecData_bookmark = m_chDecData; + } else { + m_uNumOfBitsInBuffer = m_uNumOfBitsInBuffer_bookmark; + m_chDecBuffer = m_chDecBuffer_bookmark; + m_chDecBufferSize = m_chDecBufferSize_bookmark; + m_chDecData = m_chDecData_bookmark; + m_bBookmarkOn = 0; + } + }; + int bits_remain (void) { + return m_chDecBufferSize + m_uNumOfBitsInBuffer; + }; + int byte_align(void) { + int temp = 0; + if (m_uNumOfBitsInBuffer != 0) { + temp = GetBits(m_uNumOfBitsInBuffer); +#if 0 + temp = m_uNumOfBitsInBuffer; + m_uNumOfBitsInBuffer = 0; + m_chDecBuffer++; + m_chDecBufferSize -= MIN(m_chDecBufferSize,8); +#endif + } else { + // if we are byte aligned, check for 0x7f value - this will indicate + // we need to skip those bits + uint8_t readval; + readval = PeekBits(8); + if (readval == 0x7f) { + GetBits(8); + } + } + return (temp); + }; + void set_verbose(int verbose) { m_verbose = verbose; }; + private: + uint32_t m_uNumOfBitsInBuffer; + const uint8_t *m_chDecBuffer; + uint8_t m_chDecData, m_chDecData_bookmark; + uint32_t m_chDecBufferSize; + int m_bBookmarkOn; + uint32_t m_uNumOfBitsInBuffer_bookmark; + const uint8_t *m_chDecBuffer_bookmark; + uint32_t m_chDecBufferSize_bookmark; + int m_verbose; +}; + +#endif diff --git a/MP42/sfifo.c b/MP42/sfifo.c new file mode 100644 index 0000000..bbf1914 --- /dev/null +++ b/MP42/sfifo.c @@ -0,0 +1,147 @@ +/* + SFIFO 1.3 Simple portable lock-free FIFO + + (c) 2000-2002, David Olofson - free software under the terms of the LGPL 2.1 +*/ + + +/* +----------------------------------------------------------- +TODO: + * Is there a way to avoid losing one byte of buffer + space to avoid extra variables or locking? + + * Test more compilers and environments. +----------------------------------------------------------- + */ + +#include +#include + +#include "sfifo.h" + +#define free(x, y) free(x) +#define DBG(x) + + +/* + * Alloc buffer, init FIFO etc... + */ +int sfifo_init(sfifo_t *f, int size) +{ + memset(f, 0, sizeof(sfifo_t)); + + if(size > SFIFO_MAX_BUFFER_SIZE) + return -EINVAL; + + /* + * Set sufficient power-of-2 size. + * + * No, there's no bug. If you need + * room for N bytes, the buffer must + * be at least N+1 bytes. (The fifo + * can't tell 'empty' from 'full' + * without unsafe index manipulations + * otherwise.) + */ + f->size = 1; + for(; f->size <= size; f->size <<= 1) + ; + + /* Get buffer */ + if( 0 == (f->buffer = (void *)malloc(f->size)) ) + return -ENOMEM; + + return 0; +} + +/* + * Dealloc buffer etc... + */ +void sfifo_close(sfifo_t *f) +{ + if(f->buffer) + free(f->buffer, f->size); +} + +/* + * Empty FIFO buffer + */ +void sfifo_flush(sfifo_t *f) +{ + /* Reset positions */ + f->readpos = 0; + f->writepos = 0; +} + +/* + * Write bytes to a FIFO + * Return number of bytes written, or an error code + */ +int sfifo_write(sfifo_t *f, const void *_buf, int len) +{ + int total; + int i; + const char *buf = (const char *)_buf; + + if(!f->buffer) + return -ENODEV; /* No buffer! */ + + /* total = len = min(space, len) */ + total = sfifo_space(f); + DBG(printf("sfifo_space() = %d\n",total)); + if(len > total) + len = total; + else + total = len; + + i = f->writepos; + if(i + len > f->size) + { + memcpy(f->buffer + i, buf, f->size - i); + buf += f->size - i; + len -= f->size - i; + i = 0; + } + memcpy(f->buffer + i, buf, len); + f->writepos = i + len; + + return total; +} + + +/* + * Read bytes from a FIFO + * Return number of bytes read, or an error code + */ +int sfifo_read(sfifo_t *f, void *_buf, int len) +{ + int total; + int i; + char *buf = (char *)_buf; + + if(!f->buffer) + return -ENODEV; /* No buffer! */ + + /* total = len = min(used, len) */ + total = sfifo_used(f); + DBG(printf("sfifo_used() = %d\n",total)); + if(len > total) + len = total; + else + total = len; + + i = f->readpos; + if(i + len > f->size) + { + memcpy(buf, f->buffer + i, f->size - i); + buf += f->size - i; + len -= f->size - i; + i = 0; + } + memcpy(buf, f->buffer + i, len); + f->readpos = i + len; + + return total; +} + diff --git a/MP42/sfifo.h b/MP42/sfifo.h new file mode 100644 index 0000000..d5e642c --- /dev/null +++ b/MP42/sfifo.h @@ -0,0 +1,88 @@ +/* + SFIFO 1.3 Simple portable lock-free FIFO + + (c) 2000-2002, David Olofson - free software under the terms of the LGPL 2.1 +*/ + + +/* + * Platform support: + * gcc / Linux / x86: Works + * gcc / Linux / x86 kernel: Works + * gcc / FreeBSD / x86: Works + * gcc / NetBSD / x86: Works + * gcc / Mac OS X / PPC: Works + * gcc / Win32 / x86: Works + * Borland C++ / DOS / x86RM: Works + * Borland C++ / Win32 / x86PM16: Untested + * ? / Various Un*ces / ?: Untested + * ? / Mac OS / PPC: Untested + * gcc / BeOS / x86: Untested + * gcc / BeOS / PPC: Untested + * ? / ? / Alpha: Untested + * + * 1.2: Max buffer size halved, to avoid problems with + * the sign bit... + * + * 1.3: Critical buffer allocation bug fixed! For certain + * requested buffer sizes, older version would + * allocate a buffer of insufficient size, which + * would result in memory thrashing. (Amazing that + * I've manage to use this to the extent I have + * without running into this... *heh*) + */ + +#ifndef _SFIFO_H_ +#define _SFIFO_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/*------------------------------------------------ + "Private" stuff +------------------------------------------------*/ +/* + * Porting note: + * Reads and writes of a variable of this type in memory + * must be *atomic*! 'int' is *not* atomic on all platforms. + * A safe type should be used, and sfifo should limit the + * maximum buffer size accordingly. + */ +typedef int sfifo_atomic_t; +#ifdef __TURBOC__ +# define SFIFO_MAX_BUFFER_SIZE 0x7fff +#else /* Kludge: Assume 32 bit platform */ +# define SFIFO_MAX_BUFFER_SIZE 0x7fffffff +#endif + +typedef struct sfifo_t +{ + char *buffer; + int size; /* Number of bytes */ + sfifo_atomic_t readpos; /* Read position */ + sfifo_atomic_t writepos; /* Write position */ +} sfifo_t; + +#define SFIFO_SIZEMASK(x) ((x)->size - 1) + + +/*------------------------------------------------ + API +------------------------------------------------*/ +int sfifo_init(sfifo_t *f, int size); +void sfifo_close(sfifo_t *f); +void sfifo_flush(sfifo_t *f); +int sfifo_write(sfifo_t *f, const void *buf, int len); +int sfifo_read(sfifo_t *f, void *buf, int len); +#define sfifo_used(x) (((x)->writepos - (x)->readpos) & SFIFO_SIZEMASK(x)) +#define sfifo_space(x) ((x)->size - 1 - sfifo_used(x)) +#define sfifo_size(x) ((x)->size - 1) + + +#ifdef __cplusplus +}; +#endif +#endif diff --git a/Tesseract/include/tesseract/baseapi.h b/Tesseract/include/tesseract/baseapi.h new file mode 100644 index 0000000..a52c41d --- /dev/null +++ b/Tesseract/include/tesseract/baseapi.h @@ -0,0 +1,793 @@ +/////////////////////////////////////////////////////////////////////// +// File: baseapi.h +// Description: Simple API for calling tesseract. +// Author: Ray Smith +// Created: Fri Oct 06 15:35:01 PDT 2006 +// +// (C) Copyright 2006, Google Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/////////////////////////////////////////////////////////////////////// + +#ifndef TESSERACT_API_BASEAPI_H__ +#define TESSERACT_API_BASEAPI_H__ + +#include +// To avoid collision with other typenames include the ABSOLUTE MINIMUM +// complexity of includes here. Use forward declarations wherever possible +// and hide includes of complex types in baseapi.cpp. +#include "platform.h" +#include "apitypes.h" +#include "thresholder.h" +#include "unichar.h" +#include "tesscallback.h" +#include "publictypes.h" +#include "pageiterator.h" +#include "resultiterator.h" + +template class GenericVector; +class PAGE_RES; +class PAGE_RES_IT; +class ParagraphModel; +class BlamerBundle; +class BLOCK_LIST; +class DENORM; +class IMAGE; +class MATRIX; +class PBLOB; +class ROW; +class STRING; +class WERD; +struct Pix; +struct Box; +struct Pixa; +struct Boxa; +class ETEXT_DESC; +struct OSResults; +class TBOX; +class UNICHARSET; + +// From oldlist.h +// TODO(antonova): remove when oldlist is deprecated. +struct list_rec; +typedef list_rec *LIST; + +#define MAX_NUM_INT_FEATURES 512 +struct INT_FEATURE_STRUCT; +typedef INT_FEATURE_STRUCT *INT_FEATURE; +typedef INT_FEATURE_STRUCT INT_FEATURE_ARRAY[MAX_NUM_INT_FEATURES]; +struct TBLOB; + +namespace tesseract { + +class CubeRecoContext; +class Dawg; +class Dict; +class EquationDetect; +class LTRResultIterator; +class MutableIterator; +class Tesseract; +class Trie; +class Wordrec; + +typedef int (Dict::*DictFunc)(void* void_dawg_args, + UNICHAR_ID unichar_id, bool word_end) const; +typedef double (Dict::*ProbabilityInContextFunc)(const char* lang, + const char* context, + int context_bytes, + const char* character, + int character_bytes); +typedef void (Wordrec::*FillLatticeFunc)(const MATRIX &ratings, + const LIST &best_choices, + const UNICHARSET &unicharset, + BlamerBundle *blamer_bundle); +typedef TessCallback3 TruthCallback; + +/** + * Base class for all tesseract APIs. + * Specific classes can add ability to work on different inputs or produce + * different outputs. + * This class is mostly an interface layer on top of the Tesseract instance + * class to hide the data types so that users of this class don't have to + * include any other Tesseract headers. + */ +class TESS_API TessBaseAPI { + public: + TessBaseAPI(); + virtual ~TessBaseAPI(); + + /** + * Returns the version identifier as a static string. Do not delete. + */ + static const char* Version(); + + /** + * Set the name of the input file. Needed only for training and + * reading a UNLV zone file. + */ + void SetInputName(const char* name); + + /** Set the name of the bonus output files. Needed only for debugging. */ + void SetOutputName(const char* name); + + /** + * Set the value of an internal "parameter." + * Supply the name of the parameter and the value as a string, just as + * you would in a config file. + * Returns false if the name lookup failed. + * Eg SetVariable("tessedit_char_blacklist", "xyz"); to ignore x, y and z. + * Or SetVariable("classify_bln_numeric_mode", "1"); to set numeric-only mode. + * SetVariable may be used before Init, but settings will revert to + * defaults on End(). + * TODO(rays) Add a command-line option to dump the parameters to stdout + * and add a pointer to it in the FAQ + * + * Note: Must be called after Init(). Only works for non-init variables + * (init variables should be passed to Init()). + */ + bool SetVariable(const char* name, const char* value); + bool SetDebugVariable(const char* name, const char* value); + + /** + * Returns true if the parameter was found among Tesseract parameters. + * Fills in value with the value of the parameter. + */ + bool GetIntVariable(const char *name, int *value) const; + bool GetBoolVariable(const char *name, bool *value) const; + bool GetDoubleVariable(const char *name, double *value) const; + + /** + * Returns the pointer to the string that represents the value of the + * parameter if it was found among Tesseract parameters. + */ + const char *GetStringVariable(const char *name) const; + + /** + * Print Tesseract parameters to the given file. + */ + void PrintVariables(FILE *fp) const; + + /** + * Get value of named variable as a string, if it exists. + */ + bool GetVariableAsString(const char *name, STRING *val); + + /** + * Instances are now mostly thread-safe and totally independent, + * but some global parameters remain. Basically it is safe to use multiple + * TessBaseAPIs in different threads in parallel, UNLESS: + * you use SetVariable on some of the Params in classify and textord. + * If you do, then the effect will be to change it for all your instances. + * + * Start tesseract. Returns zero on success and -1 on failure. + * NOTE that the only members that may be called before Init are those + * listed above here in the class definition. + * + * The datapath must be the name of the parent directory of tessdata and + * must end in / . Any name after the last / will be stripped. + * The language is (usually) an ISO 639-3 string or NULL will default to eng. + * It is entirely safe (and eventually will be efficient too) to call + * Init multiple times on the same instance to change language, or just + * to reset the classifier. + * The language may be a string of the form [~][+[~]]* indicating + * that multiple languages are to be loaded. Eg hin+eng will load Hindi and + * English. Languages may specify internally that they want to be loaded + * with one or more other languages, so the ~ sign is available to override + * that. Eg if hin were set to load eng by default, then hin+~eng would force + * loading only hin. The number of loaded languages is limited only by + * memory, with the caveat that loading additional languages will impact + * both speed and accuracy, as there is more work to do to decide on the + * applicable language, and there is more chance of hallucinating incorrect + * words. + * WARNING: On changing languages, all Tesseract parameters are reset + * back to their default values. (Which may vary between languages.) + * If you have a rare need to set a Variable that controls + * initialization for a second call to Init you should explicitly + * call End() and then use SetVariable before Init. This is only a very + * rare use case, since there are very few uses that require any parameters + * to be set before Init. + * + * If set_only_non_debug_params is true, only params that do not contain + * "debug" in the name will be set. + */ + int Init(const char* datapath, const char* language, OcrEngineMode mode, + char **configs, int configs_size, + const GenericVector *vars_vec, + const GenericVector *vars_values, + bool set_only_non_debug_params); + int Init(const char* datapath, const char* language, OcrEngineMode oem) { + return Init(datapath, language, oem, NULL, 0, NULL, NULL, false); + } + int Init(const char* datapath, const char* language) { + return Init(datapath, language, OEM_DEFAULT, NULL, 0, NULL, NULL, false); + } + + /** + * Returns the languages string used in the last valid initialization. + * If the last initialization specified "deu+hin" then that will be + * returned. If hin loaded eng automatically as well, then that will + * not be included in this list. To find the languages actually + * loaded use GetLoadedLanguagesAsVector. + * The returned string should NOT be deleted. + */ + const char* GetInitLanguagesAsString() const; + + /** + * Returns the loaded languages in the vector of STRINGs. + * Includes all languages loaded by the last Init, including those loaded + * as dependencies of other loaded languages. + */ + void GetLoadedLanguagesAsVector(GenericVector* langs) const; + + /** + * Returns the available languages in the vector of STRINGs. + */ + void GetAvailableLanguagesAsVector(GenericVector* langs) const; + + /** + * Init only the lang model component of Tesseract. The only functions + * that work after this init are SetVariable and IsValidWord. + * WARNING: temporary! This function will be removed from here and placed + * in a separate API at some future time. + */ + int InitLangMod(const char* datapath, const char* language); + + /** + * Init only for page layout analysis. Use only for calls to SetImage and + * AnalysePage. Calls that attempt recognition will generate an error. + */ + void InitForAnalysePage(); + + /** + * Read a "config" file containing a set of param, value pairs. + * Searches the standard places: tessdata/configs, tessdata/tessconfigs + * and also accepts a relative or absolute path name. + * Note: only non-init params will be set (init params are set by Init()). + */ + void ReadConfigFile(const char* filename); + /** Same as above, but only set debug params from the given config file. */ + void ReadDebugConfigFile(const char* filename); + + /** + * Set the current page segmentation mode. Defaults to PSM_SINGLE_BLOCK. + * The mode is stored as an IntParam so it can also be modified by + * ReadConfigFile or SetVariable("tessedit_pageseg_mode", mode as string). + */ + void SetPageSegMode(PageSegMode mode); + + /** Return the current page segmentation mode. */ + PageSegMode GetPageSegMode() const; + + /** + * Recognize a rectangle from an image and return the result as a string. + * May be called many times for a single Init. + * Currently has no error checking. + * Greyscale of 8 and color of 24 or 32 bits per pixel may be given. + * Palette color images will not work properly and must be converted to + * 24 bit. + * Binary images of 1 bit per pixel may also be given but they must be + * byte packed with the MSB of the first byte being the first pixel, and a + * 1 represents WHITE. For binary images set bytes_per_pixel=0. + * The recognized text is returned as a char* which is coded + * as UTF8 and must be freed with the delete [] operator. + * + * Note that TesseractRect is the simplified convenience interface. + * For advanced uses, use SetImage, (optionally) SetRectangle, Recognize, + * and one or more of the Get*Text functions below. + */ + char* TesseractRect(const unsigned char* imagedata, + int bytes_per_pixel, int bytes_per_line, + int left, int top, int width, int height); + + /** + * Call between pages or documents etc to free up memory and forget + * adaptive data. + */ + void ClearAdaptiveClassifier(); + + /** + * @defgroup AdvancedAPI Advanced API + * The following methods break TesseractRect into pieces, so you can + * get hold of the thresholded image, get the text in different formats, + * get bounding boxes, confidences etc. + */ + /* @{ */ + + /** + * Provide an image for Tesseract to recognize. Format is as + * TesseractRect above. Does not copy the image buffer, or take + * ownership. The source image may be destroyed after Recognize is called, + * either explicitly or implicitly via one of the Get*Text functions. + * SetImage clears all recognition results, and sets the rectangle to the + * full image, so it may be followed immediately by a GetUTF8Text, and it + * will automatically perform recognition. + */ + void SetImage(const unsigned char* imagedata, int width, int height, + int bytes_per_pixel, int bytes_per_line); + + /** + * Provide an image for Tesseract to recognize. As with SetImage above, + * Tesseract doesn't take a copy or ownership or pixDestroy the image, so + * it must persist until after Recognize. + * Pix vs raw, which to use? + * Use Pix where possible. A future version of Tesseract may choose to use Pix + * as its internal representation and discard IMAGE altogether. + * Because of that, an implementation that sources and targets Pix may end up + * with less copies than an implementation that does not. + */ + void SetImage(const Pix* pix); + + /** + * Set the resolution of the source image in pixels per inch so font size + * information can be calculated in results. Call this after SetImage(). + */ + void SetSourceResolution(int ppi); + + /** + * Restrict recognition to a sub-rectangle of the image. Call after SetImage. + * Each SetRectangle clears the recogntion results so multiple rectangles + * can be recognized with the same image. + */ + void SetRectangle(int left, int top, int width, int height); + + /** + * In extreme cases only, usually with a subclass of Thresholder, it + * is possible to provide a different Thresholder. The Thresholder may + * be preloaded with an image, settings etc, or they may be set after. + * Note that Tesseract takes ownership of the Thresholder and will + * delete it when it it is replaced or the API is destructed. + */ + void SetThresholder(ImageThresholder* thresholder) { + if (thresholder_ != NULL) + delete thresholder_; + thresholder_ = thresholder; + ClearResults(); + } + + /** + * Get a copy of the internal thresholded image from Tesseract. + * Caller takes ownership of the Pix and must pixDestroy it. + * May be called any time after SetImage, or after TesseractRect. + */ + Pix* GetThresholdedImage(); + + /** + * Get the result of page layout analysis as a leptonica-style + * Boxa, Pixa pair, in reading order. + * Can be called before or after Recognize. + */ + Boxa* GetRegions(Pixa** pixa); + + /** + * Get the textlines as a leptonica-style + * Boxa, Pixa pair, in reading order. + * Can be called before or after Recognize. + * If blockids is not NULL, the block-id of each line is also returned + * as an array of one element per line. delete [] after use. + */ + Boxa* GetTextlines(Pixa** pixa, int** blockids); + + /** + * Get textlines and strips of image regions as a leptonica-style Boxa, Pixa + * pair, in reading order. Enables downstream handling of non-rectangular + * regions. + * Can be called before or after Recognize. + * If blockids is not NULL, the block-id of each line is also returned as an + * array of one element per line. delete [] after use. + */ + Boxa* GetStrips(Pixa** pixa, int** blockids); + + /** + * Get the words as a leptonica-style + * Boxa, Pixa pair, in reading order. + * Can be called before or after Recognize. + */ + Boxa* GetWords(Pixa** pixa); + + /** + * Gets the individual connected (text) components (created + * after pages segmentation step, but before recognition) + * as a leptonica-style Boxa, Pixa pair, in reading order. + * Can be called before or after Recognize. + * Note: the caller is responsible for calling boxaDestroy() + * on the returned Boxa array and pixaDestroy() on cc array. + */ + Boxa* GetConnectedComponents(Pixa** cc); + + /** + * Get the given level kind of components (block, textline, word etc.) as a + * leptonica-style Boxa, Pixa pair, in reading order. + * Can be called before or after Recognize. + * If blockids is not NULL, the block-id of each component is also returned + * as an array of one element per component. delete [] after use. + * If text_only is true, then only text components are returned. + */ + Boxa* GetComponentImages(PageIteratorLevel level, + bool text_only, + Pixa** pixa, int** blockids); + + /** + * Returns the scale factor of the thresholded image that would be returned by + * GetThresholdedImage() and the various GetX() methods that call + * GetComponentImages(). + * Returns 0 if no thresholder has been set. + */ + int GetThresholdedImageScaleFactor() const; + + /** + * Dump the internal binary image to a PGM file. + * @deprecated Use GetThresholdedImage and write the image using pixWrite + * instead if possible. + */ + void DumpPGM(const char* filename); + + /** + * Runs page layout analysis in the mode set by SetPageSegMode. + * May optionally be called prior to Recognize to get access to just + * the page layout results. Returns an iterator to the results. + * Returns NULL on error. + * The returned iterator must be deleted after use. + * WARNING! This class points to data held within the TessBaseAPI class, and + * therefore can only be used while the TessBaseAPI class still exists and + * has not been subjected to a call of Init, SetImage, Recognize, Clear, End + * DetectOS, or anything else that changes the internal PAGE_RES. + */ + PageIterator* AnalyseLayout(); + + /** + * Recognize the image from SetAndThresholdImage, generating Tesseract + * internal structures. Returns 0 on success. + * Optional. The Get*Text functions below will call Recognize if needed. + * After Recognize, the output is kept internally until the next SetImage. + */ + int Recognize(ETEXT_DESC* monitor); + + /** + * Methods to retrieve information after SetAndThresholdImage(), + * Recognize() or TesseractRect(). (Recognize is called implicitly if needed.) + */ + + /** Variant on Recognize used for testing chopper. */ + int RecognizeForChopTest(ETEXT_DESC* monitor); + + /** + * Recognizes all the pages in the named file, as a multi-page tiff or + * list of filenames, or single image, and gets the appropriate kind of text + * according to parameters: tessedit_create_boxfile, + * tessedit_make_boxes_from_boxes, tessedit_write_unlv, tessedit_create_hocr. + * Calls ProcessPage on each page in the input file, which may be a + * multi-page tiff, single-page other file format, or a plain text list of + * images to read. If tessedit_page_number is non-negative, processing begins + * at that page of a multi-page tiff file, or filelist. + * The text is returned in text_out. Returns false on error. + * If non-zero timeout_millisec terminates processing after the timeout on + * a single page. + * If non-NULL and non-empty, and some page fails for some reason, + * the page is reprocessed with the retry_config config file. Useful + * for interactively debugging a bad page. + */ + bool ProcessPages(const char* filename, + const char* retry_config, int timeout_millisec, + STRING* text_out); + + /** + * Recognizes a single page for ProcessPages, appending the text to text_out. + * The pix is the image processed - filename and page_index are metadata + * used by side-effect processes, such as reading a box file or formatting + * as hOCR. + * If non-zero timeout_millisec terminates processing after the timeout. + * If non-NULL and non-empty, and some page fails for some reason, + * the page is reprocessed with the retry_config config file. Useful + * for interactively debugging a bad page. + * The text is returned in text_out. Returns false on error. + */ + bool ProcessPage(Pix* pix, int page_index, const char* filename, + const char* retry_config, int timeout_millisec, + STRING* text_out); + + /** + * Get a reading-order iterator to the results of LayoutAnalysis and/or + * Recognize. The returned iterator must be deleted after use. + * WARNING! This class points to data held within the TessBaseAPI class, and + * therefore can only be used while the TessBaseAPI class still exists and + * has not been subjected to a call of Init, SetImage, Recognize, Clear, End + * DetectOS, or anything else that changes the internal PAGE_RES. + */ + ResultIterator* GetIterator(); + + /** + * Get a mutable iterator to the results of LayoutAnalysis and/or Recognize. + * The returned iterator must be deleted after use. + * WARNING! This class points to data held within the TessBaseAPI class, and + * therefore can only be used while the TessBaseAPI class still exists and + * has not been subjected to a call of Init, SetImage, Recognize, Clear, End + * DetectOS, or anything else that changes the internal PAGE_RES. + */ + MutableIterator* GetMutableIterator(); + + /** + * The recognized text is returned as a char* which is coded + * as UTF8 and must be freed with the delete [] operator. + */ + char* GetUTF8Text(); + + /** + * Make a HTML-formatted string with hOCR markup from the internal + * data structures. + * page_number is 0-based but will appear in the output as 1-based. + */ + char* GetHOCRText(int page_number); + /** + * The recognized text is returned as a char* which is coded in the same + * format as a box file used in training. Returned string must be freed with + * the delete [] operator. + * Constructs coordinates in the original image - not just the rectangle. + * page_number is a 0-based page index that will appear in the box file. + */ + char* GetBoxText(int page_number); + /** + * The recognized text is returned as a char* which is coded + * as UNLV format Latin-1 with specific reject and suspect codes + * and must be freed with the delete [] operator. + */ + char* GetUNLVText(); + /** Returns the (average) confidence value between 0 and 100. */ + int MeanTextConf(); + /** + * Returns all word confidences (between 0 and 100) in an array, terminated + * by -1. The calling function must delete [] after use. + * The number of confidences should correspond to the number of space- + * delimited words in GetUTF8Text. + */ + int* AllWordConfidences(); + + /** + * Applies the given word to the adaptive classifier if possible. + * The word must be SPACE-DELIMITED UTF-8 - l i k e t h i s , so it can + * tell the boundaries of the graphemes. + * Assumes that SetImage/SetRectangle have been used to set the image + * to the given word. The mode arg should be PSM_SINGLE_WORD or + * PSM_CIRCLE_WORD, as that will be used to control layout analysis. + * The currently set PageSegMode is preserved. + * Returns false if adaption was not possible for some reason. + */ + bool AdaptToWordStr(PageSegMode mode, const char* wordstr); + + /** + * Free up recognition results and any stored image data, without actually + * freeing any recognition data that would be time-consuming to reload. + * Afterwards, you must call SetImage or TesseractRect before doing + * any Recognize or Get* operation. + */ + void Clear(); + + /** + * Close down tesseract and free up all memory. End() is equivalent to + * destructing and reconstructing your TessBaseAPI. + * Once End() has been used, none of the other API functions may be used + * other than Init and anything declared above it in the class definition. + */ + void End(); + + /** + * Check whether a word is valid according to Tesseract's language model + * @return 0 if the word is invalid, non-zero if valid. + * @warning temporary! This function will be removed from here and placed + * in a separate API at some future time. + */ + int IsValidWord(const char *word); + + bool GetTextDirection(int* out_offset, float* out_slope); + + /** Sets Dict::letter_is_okay_ function to point to the given function. */ + void SetDictFunc(DictFunc f); + + /** Sets Dict::probability_in_context_ function to point to the given + * function. + */ + void SetProbabilityInContextFunc(ProbabilityInContextFunc f); + + /** Sets Wordrec::fill_lattice_ function to point to the given function. */ + void SetFillLatticeFunc(FillLatticeFunc f); + + /** + * Estimates the Orientation And Script of the image. + * @return true if the image was processed successfully. + */ + bool DetectOS(OSResults*); + + /** This method returns the features associated with the input image. */ + void GetFeaturesForBlob(TBLOB* blob, const DENORM& denorm, + INT_FEATURE_ARRAY int_features, + int* num_features, int* FeatureOutlineIndex); + + /** + * This method returns the row to which a box of specified dimensions would + * belong. If no good match is found, it returns NULL. + */ + static ROW* FindRowForBox(BLOCK_LIST* blocks, int left, int top, + int right, int bottom); + + /** + * Method to run adaptive classifier on a blob. + * It returns at max num_max_matches results. + */ + void RunAdaptiveClassifier(TBLOB* blob, const DENORM& denorm, + int num_max_matches, + int* unichar_ids, + float* ratings, + int* num_matches_returned); + + /** This method returns the string form of the specified unichar. */ + const char* GetUnichar(int unichar_id); + + /** Return the pointer to the i-th dawg loaded into tesseract_ object. */ + const Dawg *GetDawg(int i) const; + + /** Return the number of dawgs loaded into tesseract_ object. */ + int NumDawgs() const; + + /** Returns a ROW object created from the input row specification. */ + static ROW *MakeTessOCRRow(float baseline, float xheight, + float descender, float ascender); + + /** Returns a TBLOB corresponding to the entire input image. */ + static TBLOB *MakeTBLOB(Pix *pix); + + /** + * This method baseline normalizes a TBLOB in-place. The input row is used + * for normalization. The denorm is an optional parameter in which the + * normalization-antidote is returned. + */ + static void NormalizeTBLOB(TBLOB *tblob, ROW *row, + bool numeric_mode, DENORM *denorm); + + Tesseract* const tesseract() const { + return tesseract_; + } + + OcrEngineMode const oem() const { + return last_oem_requested_; + } + + void InitTruthCallback(TruthCallback *cb) { truth_cb_ = cb; } + + /** Return a pointer to underlying CubeRecoContext object if present. */ + CubeRecoContext *GetCubeRecoContext() const; + + void set_min_orientation_margin(double margin); + + /** + * Return text orientation of each block as determined by an earlier run + * of layout analysis. + */ + void GetBlockTextOrientations(int** block_orientation, + bool** vertical_writing); + + /** Find lines from the image making the BLOCK_LIST. */ + BLOCK_LIST* FindLinesCreateBlockList(); + + /** + * Delete a block list. + * This is to keep BLOCK_LIST pointer opaque + * and let go of including the other headers. + */ + static void DeleteBlockList(BLOCK_LIST* block_list); + /* @} */ + + protected: + + /** Common code for setting the image. Returns true if Init has been called. */ + TESS_LOCAL bool InternalSetImage(); + + /** + * Run the thresholder to make the thresholded image. If pix is not NULL, + * the source is thresholded to pix instead of the internal IMAGE. + */ + TESS_LOCAL virtual void Threshold(Pix** pix); + + /** + * Find lines from the image making the BLOCK_LIST. + * @return 0 on success. + */ + TESS_LOCAL int FindLines(); + + /** Delete the pageres and block list ready for a new page. */ + TESS_LOCAL void ClearResults(); + + /** + * Return an LTR Result Iterator -- used only for training, as we really want + * to ignore all BiDi smarts at that point. + * delete once you're done with it. + */ + TESS_LOCAL LTRResultIterator* GetLTRIterator(); + + /** + * Return the length of the output text string, as UTF8, assuming + * one newline per line and one per block, with a terminator, + * and assuming a single character reject marker for each rejected character. + * Also return the number of recognized blobs in blob_count. + */ + TESS_LOCAL int TextLength(int* blob_count); + + /** @defgroup ocropusAddOns ocropus add-ons */ + /* @{ */ + + /** + * Adapt to recognize the current image as the given character. + * The image must be preloaded and be just an image of a single character. + */ + TESS_LOCAL void AdaptToCharacter(const char *unichar_repr, + int length, + float baseline, + float xheight, + float descender, + float ascender); + + /** Recognize text doing one pass only, using settings for a given pass. */ + TESS_LOCAL PAGE_RES* RecognitionPass1(BLOCK_LIST* block_list); + TESS_LOCAL PAGE_RES* RecognitionPass2(BLOCK_LIST* block_list, PAGE_RES* pass1_result); + + //// paragraphs.cpp //////////////////////////////////////////////////// + TESS_LOCAL void DetectParagraphs(bool after_text_recognition); + + /** + * Extract the OCR results, costs (penalty points for uncertainty), + * and the bounding boxes of the characters. + */ + TESS_LOCAL static int TesseractExtractResult(char** text, + int** lengths, + float** costs, + int** x0, + int** y0, + int** x1, + int** y1, + PAGE_RES* page_res); + + TESS_LOCAL const PAGE_RES* GetPageRes() const { + return page_res_; + }; + /* @} */ + + protected: + Tesseract* tesseract_; ///< The underlying data object. + Tesseract* osd_tesseract_; ///< For orientation & script detection. + EquationDetect* equ_detect_; ///* paragraph_models_; + BLOCK_LIST* block_list_; ///< The page layout. + PAGE_RES* page_res_; ///< The page-level data. + STRING* input_file_; ///< Name used by training code. + STRING* output_file_; ///< Name used by debug code. + STRING* datapath_; ///< Current location of tessdata. + STRING* language_; ///< Last initialized language. + OcrEngineMode last_oem_requested_; ///< Last ocr language mode requested. + bool recognition_done_; ///< page_res_ contains recognition data. + TruthCallback *truth_cb_; /// fxn for setting truth_* in WERD_RES + + /** + * @defgroup ThresholderParams Thresholder Parameters + * Parameters saved from the Thresholder. Needed to rebuild coordinates. + */ + /* @{ */ + int rect_left_; + int rect_top_; + int rect_width_; + int rect_height_; + int image_width_; + int image_height_; + /* @} */ + +}; + +} // namespace tesseract. + +#endif // TESSERACT_API_BASEAPI_H__ diff --git a/Tesseract/lib/libjpeg.a b/Tesseract/lib/libjpeg.a new file mode 100644 index 0000000..da46052 Binary files /dev/null and b/Tesseract/lib/libjpeg.a differ diff --git a/Tesseract/lib/liblept.a b/Tesseract/lib/liblept.a new file mode 100644 index 0000000..4eb7d77 Binary files /dev/null and b/Tesseract/lib/liblept.a differ diff --git a/Tesseract/lib/libtesseract.a b/Tesseract/lib/libtesseract.a new file mode 100644 index 0000000..ccdfe21 Binary files /dev/null and b/Tesseract/lib/libtesseract.a differ diff --git a/UniversalDetector/UniversalDetector.h b/UniversalDetector/UniversalDetector.h new file mode 100644 index 0000000..1fa261a --- /dev/null +++ b/UniversalDetector/UniversalDetector.h @@ -0,0 +1,28 @@ +#import + +#define UniversalDetector SubUniversalDetector + +@interface UniversalDetector:NSObject +{ + void *detectorptr; + NSString *charset; + float confidence; +} + +-(id)init; +-(void)dealloc; + +-(void)analyzeData:(NSData *)data; +-(void)analyzeBytes:(const char *)data length:(int)len; +-(void)reset; + +-(BOOL)done; +-(NSString *)MIMECharset; +-(NSStringEncoding)encoding; +-(float)confidence; + +-(void)debugDump; + ++(UniversalDetector *)detector; + +@end diff --git a/UniversalDetector/UniversalDetector.xcodeproj/project.pbxproj b/UniversalDetector/UniversalDetector.xcodeproj/project.pbxproj new file mode 100644 index 0000000..c8a9ccd --- /dev/null +++ b/UniversalDetector/UniversalDetector.xcodeproj/project.pbxproj @@ -0,0 +1,754 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 1B0DDB5A0A2CB1B30009B697 /* CharDistribution.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB1A0A2CB1B30009B697 /* CharDistribution.cpp */; }; + 1B0DDB600A2CB1B30009B697 /* JpCntx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB200A2CB1B30009B697 /* JpCntx.cpp */; }; + 1B0DDB620A2CB1B30009B697 /* LangBulgarianModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB220A2CB1B30009B697 /* LangBulgarianModel.cpp */; }; + 1B0DDB630A2CB1B30009B697 /* LangCyrillicModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB230A2CB1B30009B697 /* LangCyrillicModel.cpp */; }; + 1B0DDB640A2CB1B30009B697 /* LangGreekModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB240A2CB1B30009B697 /* LangGreekModel.cpp */; }; + 1B0DDB650A2CB1B30009B697 /* LangHebrewModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB250A2CB1B30009B697 /* LangHebrewModel.cpp */; }; + 1B0DDB660A2CB1B30009B697 /* LangHungarianModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB260A2CB1B30009B697 /* LangHungarianModel.cpp */; }; + 1B0DDB670A2CB1B30009B697 /* LangThaiModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB270A2CB1B30009B697 /* LangThaiModel.cpp */; }; + 1B0DDB690A2CB1B30009B697 /* nsBig5Prober.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB290A2CB1B30009B697 /* nsBig5Prober.cpp */; }; + 1B0DDB6B0A2CB1B30009B697 /* nsCharSetProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB2B0A2CB1B30009B697 /* nsCharSetProber.cpp */; }; + 1B0DDB6E0A2CB1B30009B697 /* nsEscCharsetProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB2E0A2CB1B30009B697 /* nsEscCharsetProber.cpp */; }; + 1B0DDB700A2CB1B30009B697 /* nsEscSM.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB300A2CB1B30009B697 /* nsEscSM.cpp */; }; + 1B0DDB710A2CB1B30009B697 /* nsEUCJPProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB310A2CB1B30009B697 /* nsEUCJPProber.cpp */; }; + 1B0DDB730A2CB1B30009B697 /* nsEUCKRProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB330A2CB1B30009B697 /* nsEUCKRProber.cpp */; }; + 1B0DDB750A2CB1B30009B697 /* nsEUCTWProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB350A2CB1B30009B697 /* nsEUCTWProber.cpp */; }; + 1B0DDB770A2CB1B30009B697 /* nsGB2312Prober.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB370A2CB1B30009B697 /* nsGB2312Prober.cpp */; }; + 1B0DDB790A2CB1B30009B697 /* nsHebrewProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB390A2CB1B30009B697 /* nsHebrewProber.cpp */; }; + 1B0DDB7B0A2CB1B30009B697 /* nsLatin1Prober.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB3B0A2CB1B30009B697 /* nsLatin1Prober.cpp */; }; + 1B0DDB7D0A2CB1B30009B697 /* nsMBCSGroupProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB3D0A2CB1B30009B697 /* nsMBCSGroupProber.cpp */; }; + 1B0DDB7F0A2CB1B30009B697 /* nsMBCSSM.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB3F0A2CB1B30009B697 /* nsMBCSSM.cpp */; }; + 1B0DDB810A2CB1B30009B697 /* nsSBCharSetProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB410A2CB1B30009B697 /* nsSBCharSetProber.cpp */; }; + 1B0DDB830A2CB1B30009B697 /* nsSBCSGroupProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB430A2CB1B30009B697 /* nsSBCSGroupProber.cpp */; }; + 1B0DDB850A2CB1B30009B697 /* nsSJISProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB450A2CB1B30009B697 /* nsSJISProber.cpp */; }; + 1B0DDB8B0A2CB1B30009B697 /* nsUniversalDetector.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB4B0A2CB1B30009B697 /* nsUniversalDetector.cpp */; }; + 1B0DDB8D0A2CB1B30009B697 /* nsUTF8Prober.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB4D0A2CB1B30009B697 /* nsUTF8Prober.cpp */; }; + 1B0DDC520A2CDA3D0009B697 /* kludge.c in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDC510A2CDA3D0009B697 /* kludge.c */; }; + 1B0DDC750A2CDD2E0009B697 /* UniversalDetector.h in Headers */ = {isa = PBXBuildFile; fileRef = 1B0DDC730A2CDD2D0009B697 /* UniversalDetector.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1B0DDC760A2CDD2E0009B697 /* UniversalDetector.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDC740A2CDD2E0009B697 /* UniversalDetector.mm */; }; + 1B0DDCB20A2D0B240009B697 /* DetectorTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDCB10A2D0B240009B697 /* DetectorTest.m */; }; + 1B0DDCB30A2D0B2E0009B697 /* UniversalDetector.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8DC2EF5B0486A6940098B216 /* UniversalDetector.framework */; }; + 1B0DDD600A2D1AAD0009B697 /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0867D6A5FE840307C02AAC07 /* AppKit.framework */; }; + 1B0DDD630A2D1AC10009B697 /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0867D6A5FE840307C02AAC07 /* AppKit.framework */; }; + 3DBF4F5A0BCD397C00DA401A /* CharDistribution.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB1A0A2CB1B30009B697 /* CharDistribution.cpp */; }; + 3DBF4F5B0BCD397C00DA401A /* JpCntx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB200A2CB1B30009B697 /* JpCntx.cpp */; }; + 3DBF4F5C0BCD397C00DA401A /* LangBulgarianModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB220A2CB1B30009B697 /* LangBulgarianModel.cpp */; }; + 3DBF4F5D0BCD397C00DA401A /* LangCyrillicModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB230A2CB1B30009B697 /* LangCyrillicModel.cpp */; }; + 3DBF4F5E0BCD397C00DA401A /* LangGreekModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB240A2CB1B30009B697 /* LangGreekModel.cpp */; }; + 3DBF4F5F0BCD397C00DA401A /* LangHebrewModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB250A2CB1B30009B697 /* LangHebrewModel.cpp */; }; + 3DBF4F600BCD397C00DA401A /* LangHungarianModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB260A2CB1B30009B697 /* LangHungarianModel.cpp */; }; + 3DBF4F610BCD397C00DA401A /* LangThaiModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB270A2CB1B30009B697 /* LangThaiModel.cpp */; }; + 3DBF4F620BCD397C00DA401A /* nsBig5Prober.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB290A2CB1B30009B697 /* nsBig5Prober.cpp */; }; + 3DBF4F630BCD397C00DA401A /* nsCharSetProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB2B0A2CB1B30009B697 /* nsCharSetProber.cpp */; }; + 3DBF4F640BCD397C00DA401A /* nsEscCharsetProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB2E0A2CB1B30009B697 /* nsEscCharsetProber.cpp */; }; + 3DBF4F650BCD397C00DA401A /* nsEscSM.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB300A2CB1B30009B697 /* nsEscSM.cpp */; }; + 3DBF4F660BCD397C00DA401A /* nsEUCJPProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB310A2CB1B30009B697 /* nsEUCJPProber.cpp */; }; + 3DBF4F670BCD397C00DA401A /* nsEUCKRProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB330A2CB1B30009B697 /* nsEUCKRProber.cpp */; }; + 3DBF4F680BCD397C00DA401A /* nsEUCTWProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB350A2CB1B30009B697 /* nsEUCTWProber.cpp */; }; + 3DBF4F690BCD397C00DA401A /* nsGB2312Prober.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB370A2CB1B30009B697 /* nsGB2312Prober.cpp */; }; + 3DBF4F6A0BCD397C00DA401A /* nsHebrewProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB390A2CB1B30009B697 /* nsHebrewProber.cpp */; }; + 3DBF4F6B0BCD397C00DA401A /* nsLatin1Prober.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB3B0A2CB1B30009B697 /* nsLatin1Prober.cpp */; }; + 3DBF4F6C0BCD397C00DA401A /* nsMBCSGroupProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB3D0A2CB1B30009B697 /* nsMBCSGroupProber.cpp */; }; + 3DBF4F6D0BCD397C00DA401A /* nsMBCSSM.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB3F0A2CB1B30009B697 /* nsMBCSSM.cpp */; }; + 3DBF4F6E0BCD397C00DA401A /* nsSBCharSetProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB410A2CB1B30009B697 /* nsSBCharSetProber.cpp */; }; + 3DBF4F6F0BCD397C00DA401A /* nsSBCSGroupProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB430A2CB1B30009B697 /* nsSBCSGroupProber.cpp */; }; + 3DBF4F700BCD397C00DA401A /* nsSJISProber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB450A2CB1B30009B697 /* nsSJISProber.cpp */; }; + 3DBF4F710BCD397C00DA401A /* nsUniversalDetector.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB4B0A2CB1B30009B697 /* nsUniversalDetector.cpp */; }; + 3DBF4F720BCD397C00DA401A /* nsUTF8Prober.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDB4D0A2CB1B30009B697 /* nsUTF8Prober.cpp */; }; + 3DBF4F730BCD397C00DA401A /* kludge.c in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDC510A2CDA3D0009B697 /* kludge.c */; }; + 3DBF4F740BCD397C00DA401A /* UniversalDetector.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1B0DDC740A2CDD2E0009B697 /* UniversalDetector.mm */; }; + 3DBF4F750BCD398E00DA401A /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0867D6A5FE840307C02AAC07 /* AppKit.framework */; }; + 8DC2EF530486A6940098B216 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C1666FE841158C02AAC07 /* InfoPlist.strings */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 1B0DDCBA0A2D0C490009B697 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 0867D690FE84028FC02AAC07 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8DC2EF4F0486A6940098B216; + remoteInfo = UniversalDetector; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0867D6A5FE840307C02AAC07 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = ""; }; + 089C1667FE841158C02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = ""; }; + 1B0DDB140A2CB1B20009B697 /* ChardetInterface.htm */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.html; path = ChardetInterface.htm; sourceTree = ""; }; + 1B0DDB150A2CB1B20009B697 /* UniversalCharsetDetection.doc */ = {isa = PBXFileReference; lastKnownFileType = file; path = UniversalCharsetDetection.doc; sourceTree = ""; }; + 1B0DDB190A2CB1B30009B697 /* Big5Freq.tab */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Big5Freq.tab; sourceTree = ""; }; + 1B0DDB1A0A2CB1B30009B697 /* CharDistribution.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CharDistribution.cpp; sourceTree = ""; }; + 1B0DDB1B0A2CB1B30009B697 /* CharDistribution.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CharDistribution.h; sourceTree = ""; }; + 1B0DDB1C0A2CB1B30009B697 /* EUCKRFreq.tab */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = EUCKRFreq.tab; sourceTree = ""; }; + 1B0DDB1D0A2CB1B30009B697 /* EUCTWFreq.tab */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = EUCTWFreq.tab; sourceTree = ""; }; + 1B0DDB1E0A2CB1B30009B697 /* GB2312Freq.tab */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = GB2312Freq.tab; sourceTree = ""; }; + 1B0DDB1F0A2CB1B30009B697 /* JISFreq.tab */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = JISFreq.tab; sourceTree = ""; }; + 1B0DDB200A2CB1B30009B697 /* JpCntx.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = JpCntx.cpp; sourceTree = ""; }; + 1B0DDB210A2CB1B30009B697 /* JpCntx.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = JpCntx.h; sourceTree = ""; }; + 1B0DDB220A2CB1B30009B697 /* LangBulgarianModel.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LangBulgarianModel.cpp; sourceTree = ""; }; + 1B0DDB230A2CB1B30009B697 /* LangCyrillicModel.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LangCyrillicModel.cpp; sourceTree = ""; }; + 1B0DDB240A2CB1B30009B697 /* LangGreekModel.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LangGreekModel.cpp; sourceTree = ""; }; + 1B0DDB250A2CB1B30009B697 /* LangHebrewModel.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LangHebrewModel.cpp; sourceTree = ""; }; + 1B0DDB260A2CB1B30009B697 /* LangHungarianModel.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LangHungarianModel.cpp; sourceTree = ""; }; + 1B0DDB270A2CB1B30009B697 /* LangThaiModel.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LangThaiModel.cpp; sourceTree = ""; }; + 1B0DDB290A2CB1B30009B697 /* nsBig5Prober.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsBig5Prober.cpp; sourceTree = ""; }; + 1B0DDB2A0A2CB1B30009B697 /* nsBig5Prober.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsBig5Prober.h; sourceTree = ""; }; + 1B0DDB2B0A2CB1B30009B697 /* nsCharSetProber.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsCharSetProber.cpp; sourceTree = ""; }; + 1B0DDB2C0A2CB1B30009B697 /* nsCharSetProber.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsCharSetProber.h; sourceTree = ""; }; + 1B0DDB2D0A2CB1B30009B697 /* nsCodingStateMachine.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsCodingStateMachine.h; sourceTree = ""; }; + 1B0DDB2E0A2CB1B30009B697 /* nsEscCharsetProber.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsEscCharsetProber.cpp; sourceTree = ""; }; + 1B0DDB2F0A2CB1B30009B697 /* nsEscCharsetProber.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsEscCharsetProber.h; sourceTree = ""; }; + 1B0DDB300A2CB1B30009B697 /* nsEscSM.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsEscSM.cpp; sourceTree = ""; }; + 1B0DDB310A2CB1B30009B697 /* nsEUCJPProber.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsEUCJPProber.cpp; sourceTree = ""; }; + 1B0DDB320A2CB1B30009B697 /* nsEUCJPProber.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsEUCJPProber.h; sourceTree = ""; }; + 1B0DDB330A2CB1B30009B697 /* nsEUCKRProber.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsEUCKRProber.cpp; sourceTree = ""; }; + 1B0DDB340A2CB1B30009B697 /* nsEUCKRProber.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsEUCKRProber.h; sourceTree = ""; }; + 1B0DDB350A2CB1B30009B697 /* nsEUCTWProber.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsEUCTWProber.cpp; sourceTree = ""; }; + 1B0DDB360A2CB1B30009B697 /* nsEUCTWProber.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsEUCTWProber.h; sourceTree = ""; }; + 1B0DDB370A2CB1B30009B697 /* nsGB2312Prober.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsGB2312Prober.cpp; sourceTree = ""; }; + 1B0DDB380A2CB1B30009B697 /* nsGB2312Prober.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsGB2312Prober.h; sourceTree = ""; }; + 1B0DDB390A2CB1B30009B697 /* nsHebrewProber.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsHebrewProber.cpp; sourceTree = ""; }; + 1B0DDB3A0A2CB1B30009B697 /* nsHebrewProber.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsHebrewProber.h; sourceTree = ""; }; + 1B0DDB3B0A2CB1B30009B697 /* nsLatin1Prober.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsLatin1Prober.cpp; sourceTree = ""; }; + 1B0DDB3C0A2CB1B30009B697 /* nsLatin1Prober.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsLatin1Prober.h; sourceTree = ""; }; + 1B0DDB3D0A2CB1B30009B697 /* nsMBCSGroupProber.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsMBCSGroupProber.cpp; sourceTree = ""; }; + 1B0DDB3E0A2CB1B30009B697 /* nsMBCSGroupProber.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsMBCSGroupProber.h; sourceTree = ""; }; + 1B0DDB3F0A2CB1B30009B697 /* nsMBCSSM.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsMBCSSM.cpp; sourceTree = ""; }; + 1B0DDB400A2CB1B30009B697 /* nsPkgInt.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsPkgInt.h; sourceTree = ""; }; + 1B0DDB410A2CB1B30009B697 /* nsSBCharSetProber.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsSBCharSetProber.cpp; sourceTree = ""; }; + 1B0DDB420A2CB1B30009B697 /* nsSBCharSetProber.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsSBCharSetProber.h; sourceTree = ""; }; + 1B0DDB430A2CB1B30009B697 /* nsSBCSGroupProber.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsSBCSGroupProber.cpp; sourceTree = ""; }; + 1B0DDB440A2CB1B30009B697 /* nsSBCSGroupProber.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsSBCSGroupProber.h; sourceTree = ""; }; + 1B0DDB450A2CB1B30009B697 /* nsSJISProber.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsSJISProber.cpp; sourceTree = ""; }; + 1B0DDB460A2CB1B30009B697 /* nsSJISProber.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsSJISProber.h; sourceTree = ""; }; + 1B0DDB470A2CB1B30009B697 /* nsUdetXPCOMWrapper.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsUdetXPCOMWrapper.cpp; sourceTree = ""; }; + 1B0DDB480A2CB1B30009B697 /* nsUdetXPCOMWrapper.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsUdetXPCOMWrapper.h; sourceTree = ""; }; + 1B0DDB490A2CB1B30009B697 /* nsUniversalCharDetDll.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsUniversalCharDetDll.h; sourceTree = ""; }; + 1B0DDB4A0A2CB1B30009B697 /* nsUniversalCharDetModule.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsUniversalCharDetModule.cpp; sourceTree = ""; }; + 1B0DDB4B0A2CB1B30009B697 /* nsUniversalDetector.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsUniversalDetector.cpp; sourceTree = ""; }; + 1B0DDB4C0A2CB1B30009B697 /* nsUniversalDetector.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsUniversalDetector.h; sourceTree = ""; }; + 1B0DDB4D0A2CB1B30009B697 /* nsUTF8Prober.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = nsUTF8Prober.cpp; sourceTree = ""; }; + 1B0DDB4E0A2CB1B30009B697 /* nsUTF8Prober.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsUTF8Prober.h; sourceTree = ""; }; + 1B0DDB530A2CB1B30009B697 /* UniversalChardetTest.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = UniversalChardetTest.cpp; sourceTree = ""; }; + 1B0DDC1D0A2CC9050009B697 /* nscore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = nscore.h; sourceTree = ""; }; + 1B0DDC210A2CC9720009B697 /* prtypes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = prtypes.h; sourceTree = ""; }; + 1B0DDC240A2CC9BA0009B697 /* prcpucfg.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = prcpucfg.h; sourceTree = ""; }; + 1B0DDC260A2CCA1A0009B697 /* protypes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = protypes.h; sourceTree = ""; }; + 1B0DDC280A2CCA5D0009B697 /* prmem.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = prmem.h; sourceTree = ""; }; + 1B0DDC3E0A2CD8BD0009B697 /* nsError.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = nsError.h; sourceTree = ""; }; + 1B0DDC510A2CDA3D0009B697 /* kludge.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = kludge.c; sourceTree = ""; }; + 1B0DDC730A2CDD2D0009B697 /* UniversalDetector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UniversalDetector.h; sourceTree = ""; }; + 1B0DDC740A2CDD2E0009B697 /* UniversalDetector.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = UniversalDetector.mm; sourceTree = ""; }; + 1B0DDCAB0A2D0AD10009B697 /* DetectorTest */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = DetectorTest; sourceTree = BUILT_PRODUCTS_DIR; }; + 1B0DDCB10A2D0B240009B697 /* DetectorTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DetectorTest.m; sourceTree = ""; }; + 32DBCF5E0370ADEE00C91783 /* UniversalDetector_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UniversalDetector_Prefix.pch; sourceTree = ""; }; + 3DBF4F570BCD396800DA401A /* libuniversaldetector.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libuniversaldetector.a; sourceTree = BUILT_PRODUCTS_DIR; }; + 8DC2EF5A0486A6940098B216 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist; path = Info.plist; sourceTree = ""; }; + 8DC2EF5B0486A6940098B216 /* UniversalDetector.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = UniversalDetector.framework; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 1B0DDCA90A2D0AD10009B697 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1B0DDCB30A2D0B2E0009B697 /* UniversalDetector.framework in Frameworks */, + 1B0DDD600A2D1AAD0009B697 /* AppKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3DBF4F550BCD396800DA401A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 3DBF4F750BCD398E00DA401A /* AppKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8DC2EF560486A6940098B216 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1B0DDD630A2D1AC10009B697 /* AppKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 034768DFFF38A50411DB9C8B /* Products */ = { + isa = PBXGroup; + children = ( + 8DC2EF5B0486A6940098B216 /* UniversalDetector.framework */, + 1B0DDCAB0A2D0AD10009B697 /* DetectorTest */, + 3DBF4F570BCD396800DA401A /* libuniversaldetector.a */, + ); + name = Products; + sourceTree = ""; + }; + 0867D691FE84028FC02AAC07 /* UniversalCharDet */ = { + isa = PBXGroup; + children = ( + 08FB77AEFE84172EC02AAC07 /* Classes */, + 1B0DDB110A2CB1B20009B697 /* universalchardet */, + 1B0DDC1C0A2CC8F60009B697 /* kludge */, + 1B0DDCAD0A2D0AFD0009B697 /* DetectorTest */, + 32C88DFF0371C24200C91783 /* Other Sources */, + 089C1665FE841158C02AAC07 /* Resources */, + 0867D69AFE84028FC02AAC07 /* External Frameworks and Libraries */, + 034768DFFF38A50411DB9C8B /* Products */, + ); + name = UniversalCharDet; + sourceTree = ""; + }; + 0867D69AFE84028FC02AAC07 /* External Frameworks and Libraries */ = { + isa = PBXGroup; + children = ( + 1058C7B0FEA5585E11CA2CBB /* Linked Frameworks */, + 1058C7B2FEA5585E11CA2CBB /* Other Frameworks */, + ); + name = "External Frameworks and Libraries"; + sourceTree = ""; + }; + 089C1665FE841158C02AAC07 /* Resources */ = { + isa = PBXGroup; + children = ( + 8DC2EF5A0486A6940098B216 /* Info.plist */, + 089C1666FE841158C02AAC07 /* InfoPlist.strings */, + ); + name = Resources; + sourceTree = ""; + }; + 08FB77AEFE84172EC02AAC07 /* Classes */ = { + isa = PBXGroup; + children = ( + 1B0DDC730A2CDD2D0009B697 /* UniversalDetector.h */, + 1B0DDC740A2CDD2E0009B697 /* UniversalDetector.mm */, + ); + name = Classes; + sourceTree = ""; + }; + 1058C7B0FEA5585E11CA2CBB /* Linked Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = "Linked Frameworks"; + sourceTree = ""; + }; + 1058C7B2FEA5585E11CA2CBB /* Other Frameworks */ = { + isa = PBXGroup; + children = ( + 0867D6A5FE840307C02AAC07 /* AppKit.framework */, + ); + name = "Other Frameworks"; + sourceTree = ""; + }; + 1B0DDB110A2CB1B20009B697 /* universalchardet */ = { + isa = PBXGroup; + children = ( + 1B0DDB130A2CB1B20009B697 /* doc */, + 1B0DDB170A2CB1B20009B697 /* src */, + 1B0DDB500A2CB1B30009B697 /* tests */, + ); + path = universalchardet; + sourceTree = ""; + }; + 1B0DDB130A2CB1B20009B697 /* doc */ = { + isa = PBXGroup; + children = ( + 1B0DDB140A2CB1B20009B697 /* ChardetInterface.htm */, + 1B0DDB150A2CB1B20009B697 /* UniversalCharsetDetection.doc */, + ); + path = doc; + sourceTree = ""; + }; + 1B0DDB170A2CB1B20009B697 /* src */ = { + isa = PBXGroup; + children = ( + 1B0DDB190A2CB1B30009B697 /* Big5Freq.tab */, + 1B0DDB1A0A2CB1B30009B697 /* CharDistribution.cpp */, + 1B0DDB1B0A2CB1B30009B697 /* CharDistribution.h */, + 1B0DDB1C0A2CB1B30009B697 /* EUCKRFreq.tab */, + 1B0DDB1D0A2CB1B30009B697 /* EUCTWFreq.tab */, + 1B0DDB1E0A2CB1B30009B697 /* GB2312Freq.tab */, + 1B0DDB1F0A2CB1B30009B697 /* JISFreq.tab */, + 1B0DDB200A2CB1B30009B697 /* JpCntx.cpp */, + 1B0DDB210A2CB1B30009B697 /* JpCntx.h */, + 1B0DDB220A2CB1B30009B697 /* LangBulgarianModel.cpp */, + 1B0DDB230A2CB1B30009B697 /* LangCyrillicModel.cpp */, + 1B0DDB240A2CB1B30009B697 /* LangGreekModel.cpp */, + 1B0DDB250A2CB1B30009B697 /* LangHebrewModel.cpp */, + 1B0DDB260A2CB1B30009B697 /* LangHungarianModel.cpp */, + 1B0DDB270A2CB1B30009B697 /* LangThaiModel.cpp */, + 1B0DDB290A2CB1B30009B697 /* nsBig5Prober.cpp */, + 1B0DDB2A0A2CB1B30009B697 /* nsBig5Prober.h */, + 1B0DDB2B0A2CB1B30009B697 /* nsCharSetProber.cpp */, + 1B0DDB2C0A2CB1B30009B697 /* nsCharSetProber.h */, + 1B0DDB2D0A2CB1B30009B697 /* nsCodingStateMachine.h */, + 1B0DDB2E0A2CB1B30009B697 /* nsEscCharsetProber.cpp */, + 1B0DDB2F0A2CB1B30009B697 /* nsEscCharsetProber.h */, + 1B0DDB300A2CB1B30009B697 /* nsEscSM.cpp */, + 1B0DDB310A2CB1B30009B697 /* nsEUCJPProber.cpp */, + 1B0DDB320A2CB1B30009B697 /* nsEUCJPProber.h */, + 1B0DDB330A2CB1B30009B697 /* nsEUCKRProber.cpp */, + 1B0DDB340A2CB1B30009B697 /* nsEUCKRProber.h */, + 1B0DDB350A2CB1B30009B697 /* nsEUCTWProber.cpp */, + 1B0DDB360A2CB1B30009B697 /* nsEUCTWProber.h */, + 1B0DDB370A2CB1B30009B697 /* nsGB2312Prober.cpp */, + 1B0DDB380A2CB1B30009B697 /* nsGB2312Prober.h */, + 1B0DDB390A2CB1B30009B697 /* nsHebrewProber.cpp */, + 1B0DDB3A0A2CB1B30009B697 /* nsHebrewProber.h */, + 1B0DDB3B0A2CB1B30009B697 /* nsLatin1Prober.cpp */, + 1B0DDB3C0A2CB1B30009B697 /* nsLatin1Prober.h */, + 1B0DDB3D0A2CB1B30009B697 /* nsMBCSGroupProber.cpp */, + 1B0DDB3E0A2CB1B30009B697 /* nsMBCSGroupProber.h */, + 1B0DDB3F0A2CB1B30009B697 /* nsMBCSSM.cpp */, + 1B0DDB400A2CB1B30009B697 /* nsPkgInt.h */, + 1B0DDB410A2CB1B30009B697 /* nsSBCharSetProber.cpp */, + 1B0DDB420A2CB1B30009B697 /* nsSBCharSetProber.h */, + 1B0DDB430A2CB1B30009B697 /* nsSBCSGroupProber.cpp */, + 1B0DDB440A2CB1B30009B697 /* nsSBCSGroupProber.h */, + 1B0DDB450A2CB1B30009B697 /* nsSJISProber.cpp */, + 1B0DDB460A2CB1B30009B697 /* nsSJISProber.h */, + 1B0DDB470A2CB1B30009B697 /* nsUdetXPCOMWrapper.cpp */, + 1B0DDB480A2CB1B30009B697 /* nsUdetXPCOMWrapper.h */, + 1B0DDB490A2CB1B30009B697 /* nsUniversalCharDetDll.h */, + 1B0DDB4A0A2CB1B30009B697 /* nsUniversalCharDetModule.cpp */, + 1B0DDB4B0A2CB1B30009B697 /* nsUniversalDetector.cpp */, + 1B0DDB4C0A2CB1B30009B697 /* nsUniversalDetector.h */, + 1B0DDB4D0A2CB1B30009B697 /* nsUTF8Prober.cpp */, + 1B0DDB4E0A2CB1B30009B697 /* nsUTF8Prober.h */, + ); + path = src; + sourceTree = ""; + }; + 1B0DDB500A2CB1B30009B697 /* tests */ = { + isa = PBXGroup; + children = ( + 1B0DDB530A2CB1B30009B697 /* UniversalChardetTest.cpp */, + ); + path = tests; + sourceTree = ""; + }; + 1B0DDC1C0A2CC8F60009B697 /* kludge */ = { + isa = PBXGroup; + children = ( + 1B0DDC1D0A2CC9050009B697 /* nscore.h */, + 1B0DDC210A2CC9720009B697 /* prtypes.h */, + 1B0DDC240A2CC9BA0009B697 /* prcpucfg.h */, + 1B0DDC260A2CCA1A0009B697 /* protypes.h */, + 1B0DDC280A2CCA5D0009B697 /* prmem.h */, + 1B0DDC3E0A2CD8BD0009B697 /* nsError.h */, + 1B0DDC510A2CDA3D0009B697 /* kludge.c */, + ); + path = kludge; + sourceTree = ""; + }; + 1B0DDCAD0A2D0AFD0009B697 /* DetectorTest */ = { + isa = PBXGroup; + children = ( + 1B0DDCB10A2D0B240009B697 /* DetectorTest.m */, + ); + name = DetectorTest; + sourceTree = ""; + }; + 32C88DFF0371C24200C91783 /* Other Sources */ = { + isa = PBXGroup; + children = ( + 32DBCF5E0370ADEE00C91783 /* UniversalDetector_Prefix.pch */, + ); + name = "Other Sources"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 3DBF4F530BCD396800DA401A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8DC2EF500486A6940098B216 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1B0DDC750A2CDD2E0009B697 /* UniversalDetector.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 1B0DDCAA0A2D0AD10009B697 /* DetectorTest */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1B0DDCAE0A2D0AFD0009B697 /* Build configuration list for PBXNativeTarget "DetectorTest" */; + buildPhases = ( + 1B0DDCA80A2D0AD10009B697 /* Sources */, + 1B0DDCA90A2D0AD10009B697 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 1B0DDCBB0A2D0C490009B697 /* PBXTargetDependency */, + ); + name = DetectorTest; + productName = DetectorTest; + productReference = 1B0DDCAB0A2D0AD10009B697 /* DetectorTest */; + productType = "com.apple.product-type.tool"; + }; + 3DBF4F560BCD396800DA401A /* universaldetector */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3DBF501B0BCD399D00DA401A /* Build configuration list for PBXNativeTarget "universaldetector" */; + buildPhases = ( + 3DBF4F530BCD396800DA401A /* Headers */, + 3DBF4F540BCD396800DA401A /* Sources */, + 3DBF4F550BCD396800DA401A /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = universaldetector; + productName = universaldetector; + productReference = 3DBF4F570BCD396800DA401A /* libuniversaldetector.a */; + productType = "com.apple.product-type.library.static"; + }; + 8DC2EF4F0486A6940098B216 /* UniversalDetector */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1DEB91AD08733DA50010E9CD /* Build configuration list for PBXNativeTarget "UniversalDetector" */; + buildPhases = ( + 8DC2EF500486A6940098B216 /* Headers */, + 8DC2EF520486A6940098B216 /* Resources */, + 8DC2EF540486A6940098B216 /* Sources */, + 8DC2EF560486A6940098B216 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = UniversalDetector; + productInstallPath = "$(HOME)/Library/Frameworks"; + productName = UniversalCharDet; + productReference = 8DC2EF5B0486A6940098B216 /* UniversalDetector.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 0867D690FE84028FC02AAC07 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0500; + }; + buildConfigurationList = 1DEB91B108733DA50010E9CD /* Build configuration list for PBXProject "UniversalDetector" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 1; + knownRegions = ( + en, + ); + mainGroup = 0867D691FE84028FC02AAC07 /* UniversalCharDet */; + productRefGroup = 034768DFFF38A50411DB9C8B /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 8DC2EF4F0486A6940098B216 /* UniversalDetector */, + 1B0DDCAA0A2D0AD10009B697 /* DetectorTest */, + 3DBF4F560BCD396800DA401A /* universaldetector */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 8DC2EF520486A6940098B216 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8DC2EF530486A6940098B216 /* InfoPlist.strings in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 1B0DDCA80A2D0AD10009B697 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1B0DDCB20A2D0B240009B697 /* DetectorTest.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3DBF4F540BCD396800DA401A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3DBF4F5A0BCD397C00DA401A /* CharDistribution.cpp in Sources */, + 3DBF4F5B0BCD397C00DA401A /* JpCntx.cpp in Sources */, + 3DBF4F5C0BCD397C00DA401A /* LangBulgarianModel.cpp in Sources */, + 3DBF4F5D0BCD397C00DA401A /* LangCyrillicModel.cpp in Sources */, + 3DBF4F5E0BCD397C00DA401A /* LangGreekModel.cpp in Sources */, + 3DBF4F5F0BCD397C00DA401A /* LangHebrewModel.cpp in Sources */, + 3DBF4F600BCD397C00DA401A /* LangHungarianModel.cpp in Sources */, + 3DBF4F610BCD397C00DA401A /* LangThaiModel.cpp in Sources */, + 3DBF4F620BCD397C00DA401A /* nsBig5Prober.cpp in Sources */, + 3DBF4F630BCD397C00DA401A /* nsCharSetProber.cpp in Sources */, + 3DBF4F640BCD397C00DA401A /* nsEscCharsetProber.cpp in Sources */, + 3DBF4F650BCD397C00DA401A /* nsEscSM.cpp in Sources */, + 3DBF4F660BCD397C00DA401A /* nsEUCJPProber.cpp in Sources */, + 3DBF4F670BCD397C00DA401A /* nsEUCKRProber.cpp in Sources */, + 3DBF4F680BCD397C00DA401A /* nsEUCTWProber.cpp in Sources */, + 3DBF4F690BCD397C00DA401A /* nsGB2312Prober.cpp in Sources */, + 3DBF4F6A0BCD397C00DA401A /* nsHebrewProber.cpp in Sources */, + 3DBF4F6B0BCD397C00DA401A /* nsLatin1Prober.cpp in Sources */, + 3DBF4F6C0BCD397C00DA401A /* nsMBCSGroupProber.cpp in Sources */, + 3DBF4F6D0BCD397C00DA401A /* nsMBCSSM.cpp in Sources */, + 3DBF4F6E0BCD397C00DA401A /* nsSBCharSetProber.cpp in Sources */, + 3DBF4F6F0BCD397C00DA401A /* nsSBCSGroupProber.cpp in Sources */, + 3DBF4F700BCD397C00DA401A /* nsSJISProber.cpp in Sources */, + 3DBF4F710BCD397C00DA401A /* nsUniversalDetector.cpp in Sources */, + 3DBF4F720BCD397C00DA401A /* nsUTF8Prober.cpp in Sources */, + 3DBF4F730BCD397C00DA401A /* kludge.c in Sources */, + 3DBF4F740BCD397C00DA401A /* UniversalDetector.mm in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8DC2EF540486A6940098B216 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1B0DDB5A0A2CB1B30009B697 /* CharDistribution.cpp in Sources */, + 1B0DDB600A2CB1B30009B697 /* JpCntx.cpp in Sources */, + 1B0DDB620A2CB1B30009B697 /* LangBulgarianModel.cpp in Sources */, + 1B0DDB630A2CB1B30009B697 /* LangCyrillicModel.cpp in Sources */, + 1B0DDB640A2CB1B30009B697 /* LangGreekModel.cpp in Sources */, + 1B0DDB650A2CB1B30009B697 /* LangHebrewModel.cpp in Sources */, + 1B0DDB660A2CB1B30009B697 /* LangHungarianModel.cpp in Sources */, + 1B0DDB670A2CB1B30009B697 /* LangThaiModel.cpp in Sources */, + 1B0DDB690A2CB1B30009B697 /* nsBig5Prober.cpp in Sources */, + 1B0DDB6B0A2CB1B30009B697 /* nsCharSetProber.cpp in Sources */, + 1B0DDB6E0A2CB1B30009B697 /* nsEscCharsetProber.cpp in Sources */, + 1B0DDB700A2CB1B30009B697 /* nsEscSM.cpp in Sources */, + 1B0DDB710A2CB1B30009B697 /* nsEUCJPProber.cpp in Sources */, + 1B0DDB730A2CB1B30009B697 /* nsEUCKRProber.cpp in Sources */, + 1B0DDB750A2CB1B30009B697 /* nsEUCTWProber.cpp in Sources */, + 1B0DDB770A2CB1B30009B697 /* nsGB2312Prober.cpp in Sources */, + 1B0DDB790A2CB1B30009B697 /* nsHebrewProber.cpp in Sources */, + 1B0DDB7B0A2CB1B30009B697 /* nsLatin1Prober.cpp in Sources */, + 1B0DDB7D0A2CB1B30009B697 /* nsMBCSGroupProber.cpp in Sources */, + 1B0DDB7F0A2CB1B30009B697 /* nsMBCSSM.cpp in Sources */, + 1B0DDB810A2CB1B30009B697 /* nsSBCharSetProber.cpp in Sources */, + 1B0DDB830A2CB1B30009B697 /* nsSBCSGroupProber.cpp in Sources */, + 1B0DDB850A2CB1B30009B697 /* nsSJISProber.cpp in Sources */, + 1B0DDB8B0A2CB1B30009B697 /* nsUniversalDetector.cpp in Sources */, + 1B0DDB8D0A2CB1B30009B697 /* nsUTF8Prober.cpp in Sources */, + 1B0DDC520A2CDA3D0009B697 /* kludge.c in Sources */, + 1B0DDC760A2CDD2E0009B697 /* UniversalDetector.mm in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 1B0DDCBB0A2D0C490009B697 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 8DC2EF4F0486A6940098B216 /* UniversalDetector */; + targetProxy = 1B0DDCBA0A2D0C490009B697 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 089C1666FE841158C02AAC07 /* InfoPlist.strings */ = { + isa = PBXVariantGroup; + children = ( + 089C1667FE841158C02AAC07 /* English */, + ); + name = InfoPlist.strings; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 1B0DDCAF0A2D0AFD0009B697 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + COPY_PHASE_STRIP = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = YES; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h"; + INSTALL_PATH = "$(HOME)/bin"; + OTHER_LDFLAGS = ( + "-framework", + Foundation, + "-framework", + AppKit, + ); + PRODUCT_NAME = DetectorTest; + }; + name = Debug; + }; + 1B0DDCB00A2D0AFD0009B697 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + COPY_PHASE_STRIP = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h"; + INSTALL_PATH = "$(HOME)/bin"; + OTHER_LDFLAGS = ( + "-framework", + Foundation, + "-framework", + AppKit, + ); + PRODUCT_NAME = DetectorTest; + }; + name = Release; + }; + 1DEB91AE08733DA50010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + FRAMEWORK_VERSION = A; + GCC_DYNAMIC_NO_PIC = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = UniversalDetector_Prefix.pch; + INFOPLIST_FILE = Info.plist; + INSTALL_PATH = "@executable_path/../Frameworks"; + PRODUCT_NAME = UniversalDetector; + WRAPPER_EXTENSION = framework; + }; + name = Debug; + }; + 1DEB91AF08733DA50010E9CD /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + FRAMEWORK_VERSION = A; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = UniversalDetector_Prefix.pch; + INFOPLIST_FILE = Info.plist; + INSTALL_PATH = "@executable_path/../Frameworks"; + PRODUCT_NAME = UniversalDetector; + WRAPPER_EXTENSION = framework; + }; + name = Release; + }; + 1DEB91B208733DA50010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_64_BIT)"; + DEBUG_INFORMATION_FORMAT = dwarf; + GCC_DYNAMIC_NO_PIC = YES; + GCC_ENABLE_OBJC_GC = ""; + GCC_INLINES_ARE_PRIVATE_EXTERN = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.6; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx10.8; + }; + name = Debug; + }; + 1DEB91B308733DA50010E9CD /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_64_BIT)"; + DEBUG_INFORMATION_FORMAT = dwarf; + GCC_DYNAMIC_NO_PIC = YES; + GCC_ENABLE_OBJC_GC = ""; + GCC_INLINES_ARE_PRIVATE_EXTERN = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.6; + SDKROOT = macosx10.8; + }; + name = Release; + }; + 3DBF501C0BCD399D00DA401A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + GCC_ENABLE_CPP_RTTI = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + INSTALL_PATH = /usr/local/lib; + PRODUCT_NAME = universaldetector; + }; + name = Debug; + }; + 3DBF501D0BCD399D00DA401A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + GCC_ENABLE_CPP_RTTI = NO; + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + INSTALL_PATH = /usr/local/lib; + PRODUCT_NAME = universaldetector; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1B0DDCAE0A2D0AFD0009B697 /* Build configuration list for PBXNativeTarget "DetectorTest" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1B0DDCAF0A2D0AFD0009B697 /* Debug */, + 1B0DDCB00A2D0AFD0009B697 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 1DEB91AD08733DA50010E9CD /* Build configuration list for PBXNativeTarget "UniversalDetector" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1DEB91AE08733DA50010E9CD /* Debug */, + 1DEB91AF08733DA50010E9CD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 1DEB91B108733DA50010E9CD /* Build configuration list for PBXProject "UniversalDetector" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1DEB91B208733DA50010E9CD /* Debug */, + 1DEB91B308733DA50010E9CD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 3DBF501B0BCD399D00DA401A /* Build configuration list for PBXNativeTarget "universaldetector" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 3DBF501C0BCD399D00DA401A /* Debug */, + 3DBF501D0BCD399D00DA401A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 0867D690FE84028FC02AAC07 /* Project object */; +} diff --git a/UniversalDetector/UniversalDetector.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/UniversalDetector/UniversalDetector.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..35b9181 --- /dev/null +++ b/UniversalDetector/UniversalDetector.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/UniversalDetector/UniversalDetector.xcodeproj/xcuserdata/damians.xcuserdatad/xcschemes/DetectorTest.xcscheme b/UniversalDetector/UniversalDetector.xcodeproj/xcuserdata/damians.xcuserdatad/xcschemes/DetectorTest.xcscheme new file mode 100644 index 0000000..410d100 --- /dev/null +++ b/UniversalDetector/UniversalDetector.xcodeproj/xcuserdata/damians.xcuserdatad/xcschemes/DetectorTest.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/UniversalDetector/UniversalDetector.xcodeproj/xcuserdata/damians.xcuserdatad/xcschemes/universaldetector.xcscheme b/UniversalDetector/UniversalDetector.xcodeproj/xcuserdata/damians.xcuserdatad/xcschemes/universaldetector.xcscheme new file mode 100644 index 0000000..cf77db9 --- /dev/null +++ b/UniversalDetector/UniversalDetector.xcodeproj/xcuserdata/damians.xcuserdatad/xcschemes/universaldetector.xcscheme @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/UniversalDetector/UniversalDetector.xcodeproj/xcuserdata/damians.xcuserdatad/xcschemes/xcschememanagement.plist b/UniversalDetector/UniversalDetector.xcodeproj/xcuserdata/damians.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..f1ae949 --- /dev/null +++ b/UniversalDetector/UniversalDetector.xcodeproj/xcuserdata/damians.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,42 @@ + + + + + SchemeUserState + + DetectorTest.xcscheme + + orderHint + 1 + + UniversalDetector.xcscheme + + orderHint + 0 + + universaldetector.xcscheme + + orderHint + 2 + + + SuppressBuildableAutocreation + + 1B0DDCAA0A2D0AD10009B697 + + primary + + + 3DBF4F560BCD396800DA401A + + primary + + + 8DC2EF4F0486A6940098B216 + + primary + + + + + diff --git a/ffmpeg/lib/libavcodec.a b/ffmpeg/lib/libavcodec.a new file mode 100644 index 0000000..e49d701 Binary files /dev/null and b/ffmpeg/lib/libavcodec.a differ diff --git a/ffmpeg/lib/libavdevice.a b/ffmpeg/lib/libavdevice.a new file mode 100644 index 0000000..8af6cbc Binary files /dev/null and b/ffmpeg/lib/libavdevice.a differ diff --git a/ffmpeg/lib/libavformat.a b/ffmpeg/lib/libavformat.a new file mode 100644 index 0000000..a250527 Binary files /dev/null and b/ffmpeg/lib/libavformat.a differ diff --git a/ffmpeg/lib/libavutil.a b/ffmpeg/lib/libavutil.a new file mode 100644 index 0000000..046a28a Binary files /dev/null and b/ffmpeg/lib/libavutil.a differ diff --git a/mp4v2/libmp4v2.a b/mp4v2/libmp4v2.a new file mode 100644 index 0000000..e660b5a Binary files /dev/null and b/mp4v2/libmp4v2.a differ diff --git a/mp4v2/mp4v2.h b/mp4v2/mp4v2.h new file mode 100644 index 0000000..4d8e807 --- /dev/null +++ b/mp4v2/mp4v2.h @@ -0,0 +1,83 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is MPEG4IP. + * + * The Initial Developer of the Original Code is Cisco Systems Inc. + * Portions created by Cisco Systems Inc. are + * Copyright (C) Cisco Systems Inc. 2001 - 2005. All Rights Reserved. + * + * 3GPP features implementation is based on 3GPP's TS26.234-v5.60, + * and was contributed by Ximpo Group Ltd. + * + * Portions created by Ximpo Group Ltd. are + * Copyright (C) Ximpo Group Ltd. 2003, 2004. All Rights Reserved. + * + * Contributor(s): + * Dave Mackie dmackie@cisco.com + * Alix Marchandise-Franquet alix@cisco.com + * Ximpo Group Ltd. mp4v2@ximpo.com + * Bill May wmay@cisco.com + */ +#ifndef MP4V2_MP4V2_H +#define MP4V2_MP4V2_H + +/*****************************************************************************/ + +#include +#include + +/*****************************************************************************/ + +/* exploit C++ ability of default values for function parameters */ +#if defined( DEFAULT ) +# define __MP4V2_SAVE_DEFAULT DEFAULT +#endif +#undef DEFAULT +#if defined( __cplusplus ) +# define DEFAULT(x) =x +#else +# define DEFAULT(x) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/*****************************************************************************/ + +/* restore macro DEFAULT to state prior to mp4v2 headers */ +#undef DEFAULT +#if defined( __MP4V2_SAVE_DEFAULT ) +# define DEFAULT __MP4V2_SAVE_DEFAULT +#endif + +#ifdef __cplusplus +} // extern "C" +#endif + +/*****************************************************************************/ + +#endif /* MP4V2_MP4V2_H */ diff --git a/mp4v2/mp4v2/chapter.h b/mp4v2/mp4v2/chapter.h new file mode 100644 index 0000000..0070c9c --- /dev/null +++ b/mp4v2/mp4v2/chapter.h @@ -0,0 +1,177 @@ +#ifndef MP4V2_CHAPTER_H +#define MP4V2_CHAPTER_H + +/**************************************************************************//** + * + * @defgroup mp4_chapter MP4v2 Chapter + * @{ + * + *****************************************************************************/ + +/** The maximum length of a QuickTime chapter title (in 8-bit chars) + */ +#define MP4V2_CHAPTER_TITLE_MAX 1023 + +/** Chapter item. + * This item defines various attributes for a chapter. + * @ingroup mp4_chapter + */ +typedef struct MP4Chapter_s { + MP4Duration duration; /**< duration of chapter in milliseconds */ + char title[MP4V2_CHAPTER_TITLE_MAX+1]; /**< title of chapter */ + uint32_t titleLength; +} MP4Chapter_t; + +/** Known chapter types. + * @ingroup mp4_chapter + */ +typedef enum { + MP4ChapterTypeNone = 0, /**< no chapters found return value */ + MP4ChapterTypeAny = 1, /**< any or all known chapter types */ + MP4ChapterTypeQt = 2, /**< QuickTime chapter type */ + MP4ChapterTypeNero = 4 /**< Nero chapter type */ +} MP4ChapterType; + +/** Add a QuickTime chapter. + * + * This function adds a QuickTime chapter to file hFile. + * + * @param hFile handle of file to add chapter. + * @param chapterTrackId ID of chapter track or #MP4_INVALID_TRACK_ID + * if unknown. + * @param chapterDuration duration (in the timescale of the chapter track). + * @param chapterTitle title text for the chapter or NULL to use default + * title format ("Chapter %03d", n) where n is the chapter number. + */ +MP4V2_EXPORT +void MP4AddChapter( + MP4FileHandle hFile, + MP4TrackId chapterTrackId, + MP4Duration chapterDuration, + const char* chapterTitle DEFAULT(0)); + +/** Add a QuickTime chapter track. + * + * This function adds a chapter (text) track to file hFile. + * The optional parameter timescale may be supplied to give the new + * chapter a specific timescale. Otherwise the chapter track will have + * the same timescale as the reference track defined in parameter refTrackId. + * + * @param hFile handle of file to add chapter track. + * @param refTrackId ID of the track that will reference the chapter track. + * @param timescale the timescale of the chapter track or 0 to use the + * timescale of track specified by refTrackId. + * + * @return ID of the created chapter track. + */ +MP4V2_EXPORT +MP4TrackId MP4AddChapterTextTrack( + MP4FileHandle hFile, + MP4TrackId refTrackId, + uint32_t timescale DEFAULT(0) ); + +/** Add a Nero chapter. + * + * This function adds a Nero chapter to file hFile. + * + * @param hFile handle of file to add chapter. + * @param chapterStart the start time of the chapter in 100 nanosecond units + * @param chapterTitle title text for the chapter or NULL to use default + * title format ("Chapter %03d", n) where n is the chapter number. + */ +MP4V2_EXPORT +void MP4AddNeroChapter( + MP4FileHandle hFile, + MP4Timestamp chapterStart, + const char* chapterTitle DEFAULT(0)); + +/** Convert chapters to another type. + * + * This function converts existing chapters in file hFile + * from one type to another type. + * Conversion from Nero to QuickTime or QuickTime to Nero is supported. + * + * @param hFile handle of file to convert. + * @param toChapterType the chapter type to convert to: + * @li #MP4ChapterTypeQt (convert from Nero to Qt) + * @li #MP4ChapterTypeNero (convert from Qt to Nero) + * + * @return the chapter type before conversion or #MP4ChapterTypeNone + * if the source chapters do not exist + * or invalid toChapterType was specified. + */ +MP4V2_EXPORT +MP4ChapterType MP4ConvertChapters( + MP4FileHandle hFile, + MP4ChapterType toChapterType DEFAULT(MP4ChapterTypeQt)); + +/** Delete chapters. + * + * This function deletes existing chapters in file hFile. + * + * @param hFile handle of file to delete chapters. + * @param chapterType the type of chapters to delete: + * @li #MP4ChapterTypeAny (delete all known chapter types) + * @li #MP4ChapterTypeQt + * @li #MP4ChapterTypeNero + * @param chapterTrackId ID of the chapter track if known, + * or #MP4_INVALID_TRACK_ID. + * Only applies when chapterType=#MP4ChapterTypeQt. + * + * @return the type of deleted chapters + */ +MP4V2_EXPORT +MP4ChapterType MP4DeleteChapters( + MP4FileHandle hFile, + MP4ChapterType chapterType DEFAULT(MP4ChapterTypeQt), + MP4TrackId chapterTrackId DEFAULT(MP4_INVALID_TRACK_ID) ); + +/** Get list of chapters. + * + * This function gets a chpter list from file hFile. + * + * @param hFile handle of file to read. + * @param chapterList address receiving array of chapter items. + * If a non-NULL is received the caller is responsible for freeing the + * memory with MP4Free(). + * @param chapterCount address receiving count of items in array. + * @param chapterType the type of chapters to read: + * @li #MP4ChapterTypeAny (any chapters, searched in order of Qt, Nero) + * @li #MP4ChapterTypeQt + * @li #MP4ChapterTypeNero + * + * @result the first type of chapters found. + */ +MP4V2_EXPORT +MP4ChapterType MP4GetChapters( + MP4FileHandle hFile, + MP4Chapter_t** chapterList, + uint32_t* chapterCount, + MP4ChapterType chapterType DEFAULT(MP4ChapterTypeQt)); + +/** Set list of chapters OKOK. + * + * This functions sets the complete chapter list in file hFile. + * If any chapters of the same type already exist they will first + * be deleted. + * + * @param hFile handle of file to modify. + * @param chapterList array of chapters items. + * @param chapterCount count of items in array. + * @param chapterType type of chapters to write: + * @li #MP4ChapterTypeAny (chapters of all types are written) + * @li #MP4ChapterTypeQt + * @li #MP4ChapterTypeNero + * + * @return the type of chapters written. + */ +MP4V2_EXPORT +MP4ChapterType MP4SetChapters( + MP4FileHandle hFile, + MP4Chapter_t* chapterList, + uint32_t chapterCount, + MP4ChapterType chapterType DEFAULT(MP4ChapterTypeQt)); + +/** @} ***********************************************************************/ + +#endif /* MP4V2_CHAPTER_H */ diff --git a/mp4v2/mp4v2/file.h b/mp4v2/mp4v2/file.h new file mode 100644 index 0000000..330dec9 --- /dev/null +++ b/mp4v2/mp4v2/file.h @@ -0,0 +1,362 @@ +#ifndef MP4V2_FILE_H +#define MP4V2_FILE_H + +/**************************************************************************//** + * + * @defgroup mp4_file MP4v2 File I/O + * @{ + * + *****************************************************************************/ + +/** Bit: enable 64-bit data-atoms. */ +#define MP4_CREATE_64BIT_DATA 0x01 +/** Bit: enable 64-bit time-atoms. @note Incompatible with QuickTime. */ +#define MP4_CREATE_64BIT_TIME 0x02 +/** Bit: do not recompute avg/max bitrates on file close. @note See http://code.google.com/p/mp4v2/issues/detail?id=66 */ +#define MP4_CLOSE_DO_NOT_COMPUTE_BITRATE 0x01 + +/** Enumeration of file modes for custom file provider. */ +typedef enum MP4FileMode_e +{ + FILEMODE_UNDEFINED, /**< undefined */ + FILEMODE_READ, /**< file may be read */ + FILEMODE_MODIFY, /**< file may be read/written */ + FILEMODE_CREATE /**< file will be created/truncated for read/write */ +} MP4FileMode; + +/** Structure of functions implementing custom file provider. + * + * Except for open, all the functions must return a true value + * to indicate failure or false on success. The open function must return + * a pointer or handle which represents the open file, otherwise NULL. + * + * maxChunkSize is a hint suggesting what the max size of data should be read + * as in underlying read/write operations. A value of 0 indicates there is no hint. + */ +typedef struct MP4FileProvider_s +{ + void* ( *open )( const char* name, MP4FileMode mode ); + int ( *seek )( void* handle, int64_t pos ); + int ( *read )( void* handle, void* buffer, int64_t size, int64_t* nin, int64_t maxChunkSize ); + int ( *write )( void* handle, const void* buffer, int64_t size, int64_t* nout, int64_t maxChunkSize ); + int ( *close )( void* handle ); +} MP4FileProvider; + +/** Close an mp4 file. + * MP4Close closes a previously opened mp4 file. If the file was opened + * writable with MP4Create() or MP4Modify(), then MP4Close() will write + * out all pending information to disk. + * + * @param hFile handle of file to close. + * @param flags bitmask that allows the user to set extra options for the + * close commands. Valid options include: + * @li #MP4_CLOSE_DO_NOT_COMPUTE_BITRATE + */ +MP4V2_EXPORT +bool MP4Close( + MP4FileHandle hFile, + uint32_t flags DEFAULT(0) ); + +/** Create a new mp4 file. + * + * MP4Create is the first call that should be used when you want to create + * a new, empty mp4 file. It is equivalent to opening a file for writing, + * but also involved with creation of necessary mp4 framework structures. + * ie. invoking MP4Create() followed by MP4Close() will result in a file + * with a non-zero size. + * + * @param fileName pathname of the file to be created. + * On Windows, this should be a UTF-8 encoded string. + * On other platforms, it should be an 8-bit encoding that is + * appropriate for the platform, locale, file system, etc. + * (prefer to use UTF-8 when possible). + * @param flags bitmask that allows the user to set 64-bit values for + * data or time atoms. Valid bits may be any combination of: + * @li #MP4_CREATE_64BIT_DATA + * @li #MP4_CREATE_64BIT_TIME + * + * @return On success a handle of the newly created file for use in + * subsequent calls to the library. + * On error, #MP4_INVALID_FILE_HANDLE. + */ +MP4V2_EXPORT +MP4FileHandle MP4Create( + const char* fileName, + uint32_t flags DEFAULT(0) ); + +/** Create a new mp4 file with extended options. + * + * MP4CreateEx is an extended version of MP4Create(). + * + * @param fileName pathname of the file to be created. + * On Windows, this should be a UTF-8 encoded string. + * On other platforms, it should be an 8-bit encoding that is + * appropriate for the platform, locale, file system, etc. + * (prefer to use UTF-8 when possible). + * @param flags bitmask that allows the user to set 64-bit values for + * data or time atoms. Valid bits may be any combination of: + * @li #MP4_CREATE_64BIT_DATA + * @li #MP4_CREATE_64BIT_TIME + * @param add_ftyp if true an ftyp atom is automatically created. + * @param add_iods if true an iods atom is automatically created. + * @param majorBrand ftyp brand identifier. + * @param minorVersion ftyp informative integer for the minor version + * of the major brand. + * @param compatibleBrands ftyp list of compatible brands. + * @param compatibleBrandsCount is the count of items specified in + * compatibleBrands. + * + * @return On success a handle of the newly created file for use in + * subsequent calls to the library. + * On error, #MP4_INVALID_FILE_HANDLE. + */ +MP4V2_EXPORT +MP4FileHandle MP4CreateEx( + const char* fileName, + uint32_t flags DEFAULT(0), + int add_ftyp DEFAULT(1), + int add_iods DEFAULT(1), + char* majorBrand DEFAULT(0), + uint32_t minorVersion DEFAULT(0), + char** compatibleBrands DEFAULT(0), + uint32_t compatibleBrandsCount DEFAULT(0) ); + +/** Dump mp4 file contents as ASCII either to stdout or the + * log callback (@p see MP4SetLogCallback) + * + * Dump is an invaluable debugging tool in that in can reveal all the details + * of the mp4 control structures. However, the output will not make much sense + * until you familiarize yourself with the mp4 specification (or the Quicktime + * File Format specification). + * + + * Note that MP4Dump() will not print the individual values of control tables, + * such as the size of each sample, unless the current log level is at least + * #MP4_LOG_VERBOSE2. @p see MP4LogSetLevel() for how to set this. + * + * @param hFile handle of file to dump. + * @param dumpImplicits prints properties which would not actually be + * written to the mp4 file, but still exist in mp4 control structures. + * ie. they are implicit given the current values of other controlling + * properties. + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4Dump( + MP4FileHandle hFile, + bool dumpImplicits DEFAULT(0) ); + +/** Return a textual summary of an mp4 file. + * + * MP4FileInfo provides a string that contains a textual summary of the + * contents of an mp4 file. This includes the track id's, the track type, + * and track specific information. For example, for a video track, media + * encoding, image size, frame rate, and bitrate are summarized. + * + * Note that the returned string is malloc'ed, so it is the caller's + * responsibility to free() the string. Also note that the returned string + * contains newlines and tabs which may or may not be desirable. + * + * The following is an example of the output of MP4Info(): +@verbatim +Track Type Info +1 video MPEG-4 Simple @ L3, 119.625 secs, 1008 kbps, 352x288 @ 24.00 fps +2 audio MPEG-4, 119.327 secs, 128 kbps, 44100 Hz +3 hint Payload MP4V-ES for track 1 +4 hint Payload mpeg4-generic for track 2 +5 od Object Descriptors +6 scene BIFS +@endverbatim + * + * @param fileName pathname to mp4 file to summarize. + * On Windows, this should be a UTF-8 encoded string. + * On other platforms, it should be an 8-bit encoding that is + * appropriate for the platform, locale, file system, etc. + * (prefer to use UTF-8 when possible). + * @param trackId specifies track to summarize. If the value is + * #MP4_INVALID_TRACK_ID, the summary info is created for all + * tracks in the file. + * + * @return On success a malloc'd string containing summary information. + * On failure, NULL. + * + * @see MP4Info(). + */ +MP4V2_EXPORT +char* MP4FileInfo( + const char* fileName, + MP4TrackId trackId DEFAULT(MP4_INVALID_TRACK_ID) ); + +/** Accessor for the filename associated with a file handle + * + * @param hFile a file handle + * + * @return the NUL-terminated, UTF-8 encoded filename + * associated with @p hFile + */ +MP4V2_EXPORT +const char* MP4GetFilename( + MP4FileHandle hFile ); + +/** Return a textual summary of an mp4 file. + * + * MP4FileInfo provides a string that contains a textual summary of the + * contents of an mp4 file. This includes the track id's, the track type, + * and track specific information. For example, for a video track, media + * encoding, image size, frame rate, and bitrate are summarized. + * + * Note that the returned string is malloc'ed, so it is the caller's + * responsibility to free() the string. Also note that the returned string + * contains newlines and tabs which may or may not be desirable. + * + * The following is an example of the output of MP4Info(): +@verbatim +Track Type Info +1 video MPEG-4 Simple @ L3, 119.625 secs, 1008 kbps, 352x288 @ 24.00 fps +2 audio MPEG-4, 119.327 secs, 128 kbps, 44100 Hz +3 hint Payload MP4V-ES for track 1 +4 hint Payload mpeg4-generic for track 2 +5 od Object Descriptors +6 scene BIFS +@endverbatim + * + * @param hFile handle of file to summarize. + * @param trackId specifies track to summarize. If the value is + * #MP4_INVALID_TRACK_ID, the summary info is created for all + * tracks in the file. + * + * @return On success a malloc'd string containing summary information. + * On failure, NULL. + * + * @see MP4FileInfo(). + */ +MP4V2_EXPORT +char* MP4Info( + MP4FileHandle hFile, + MP4TrackId trackId DEFAULT(MP4_INVALID_TRACK_ID) ); + +/** Modify an existing mp4 file. + * + * MP4Modify is the first call that should be used when you want to modify + * an existing mp4 file. It is roughly equivalent to opening a file in + * read/write mode. + * + * Since modifications to an existing mp4 file can result in a sub-optimal + * file layout, you may want to use MP4Optimize() after you have modified + * and closed the mp4 file. + * + * @param fileName pathname of the file to be modified. + * On Windows, this should be a UTF-8 encoded string. + * On other platforms, it should be an 8-bit encoding that is + * appropriate for the platform, locale, file system, etc. + * (prefer to use UTF-8 when possible). + * @param flags currently ignored. + * + * @return On success a handle of the target file for use in subsequent calls + * to the library. + * On error, #MP4_INVALID_FILE_HANDLE. + */ +MP4V2_EXPORT +MP4FileHandle MP4Modify( + const char* fileName, + uint32_t flags DEFAULT(0) ); + +/** Optimize the layout of an mp4 file. + * + * MP4Optimize reads an existing mp4 file and writes a new version of the + * file with the two important changes: + * + * First, the mp4 control information is moved to the beginning of the file. + * (Frequenty it is at the end of the file due to it being constantly + * modified as track samples are added to an mp4 file). This optimization + * is useful in that in allows the mp4 file to be HTTP streamed. + * + * Second, the track samples are interleaved so that the samples for a + * particular instant in time are colocated within the file. This + * eliminates disk seeks during playback of the file which results in + * better performance. + * + * There are also two important side effects of MP4Optimize(): + * + * First, any free blocks within the mp4 file are eliminated. + * + * Second, as a side effect of the sample interleaving process any media + * data chunks that are not actually referenced by the mp4 control + * structures are deleted. This is useful if you have called MP4DeleteTrack() + * which only deletes the control information for a track, and not the + * actual media data. + * + * @param fileName pathname of (existing) file to be optimized. + * On Windows, this should be a UTF-8 encoded string. + * On other platforms, it should be an 8-bit encoding that is + * appropriate for the platform, locale, file system, etc. + * (prefer to use UTF-8 when possible). + * @param newFileName pathname of the new optimized file. + * On Windows, this should be a UTF-8 encoded string. + * On other platforms, it should be an 8-bit encoding that is + * appropriate for the platform, locale, file system, etc. + * (prefer to use UTF-8 when possible). + * If NULL a temporary file in the same directory as the + * fileName will be used and fileName + * will be over-written upon successful completion. + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4Optimize( + const char* fileName, + const char* newFileName DEFAULT(NULL) ); + + +/** Read an existing mp4 file. + * + * MP4Read is the first call that should be used when you want to just + * read an existing mp4 file. It is equivalent to opening a file for + * reading, but in addition the mp4 file is parsed and the control + * information is loaded into memory. Note that actual track samples are not + * read into memory until MP4ReadSample() is called. + * + * @param fileName pathname of the file to be read. + * On Windows, this should be a UTF-8 encoded string. + * On other platforms, it should be an 8-bit encoding that is + * appropriate for the platform, locale, file system, etc. + * (prefer to use UTF-8 when possible). +( + * @return On success a handle of the file for use in subsequent calls to + * the library. + * On error, #MP4_INVALID_FILE_HANDLE. + */ +MP4V2_EXPORT +MP4FileHandle MP4Read( + const char* fileName ); + +/** Read an existing mp4 file. + * + * MP4ReadProvider is the first call that should be used when you want to just + * read an existing mp4 file. It is equivalent to opening a file for + * reading, but in addition the mp4 file is parsed and the control + * information is loaded into memory. Note that actual track samples are not + * read into memory until MP4ReadSample() is called. + * + * @param fileName pathname of the file to be read. + * On Windows, this should be a UTF-8 encoded string. + * On other platforms, it should be an 8-bit encoding that is + * appropriate for the platform, locale, file system, etc. + * (prefer to use UTF-8 when possible). + * @param fileProvider custom implementation of file I/O operations. + * All functions in structure must be implemented. + * The structure is immediately copied internally. + * + * @return On success a handle of the file for use in subsequent calls to + * the library. + * On error, #MP4_INVALID_FILE_HANDLE. + */ +MP4V2_EXPORT +MP4FileHandle MP4ReadProvider( + const char* fileName, + const MP4FileProvider* fileProvider DEFAULT(NULL) ); + +/** @} ***********************************************************************/ + +#endif /* MP4V2_FILE_H */ diff --git a/mp4v2/mp4v2/file_prop.h b/mp4v2/mp4v2/file_prop.h new file mode 100644 index 0000000..15435e8 --- /dev/null +++ b/mp4v2/mp4v2/file_prop.h @@ -0,0 +1,148 @@ +#ifndef MP4V2_FILE_PROP_H +#define MP4V2_FILE_PROP_H + +/**************************************************************************//** + * + * @defgroup mp4_file_prop MP4v2 File Property + * @{ + * + *****************************************************************************/ + +/* generic props */ + +MP4V2_EXPORT +bool MP4HaveAtom( + MP4FileHandle hFile, + const char* atomName ); + +MP4V2_EXPORT +bool MP4GetIntegerProperty( + MP4FileHandle hFile, + const char* propName, + uint64_t* retval ); + +MP4V2_EXPORT +bool MP4GetFloatProperty( + MP4FileHandle hFile, + const char* propName, + float* retvalue ); + +MP4V2_EXPORT +bool MP4GetStringProperty( + MP4FileHandle hFile, + const char* propName, + const char** retvalue ); + +MP4V2_EXPORT +bool MP4GetBytesProperty( + MP4FileHandle hFile, + const char* propName, + uint8_t** ppValue, + uint32_t* pValueSize ); + +MP4V2_EXPORT +bool MP4SetIntegerProperty( + MP4FileHandle hFile, + const char* propName, + int64_t value ); + +MP4V2_EXPORT +bool MP4SetFloatProperty( + MP4FileHandle hFile, + const char* propName, + float value ); + +MP4V2_EXPORT +bool MP4SetStringProperty( + MP4FileHandle hFile, + const char* propName, + const char* value ); + +MP4V2_EXPORT +bool MP4SetBytesProperty( + MP4FileHandle hFile, + const char* propName, + const uint8_t* pValue, + uint32_t valueSize ); + +/* specific props */ + +MP4V2_EXPORT +MP4Duration MP4GetDuration( MP4FileHandle hFile ); + +/** Get the time scale of the movie (file). + * + * MP4GetTimeScale returns the time scale in units of ticks per second for + * the mp4 file. Caveat: tracks may use the same time scale as the movie + * or may use their own time scale. + * + * @param hFile handle of file for operation. + * + * @return timescale (ticks per second) of the mp4 file. + */ +MP4V2_EXPORT +uint32_t MP4GetTimeScale( MP4FileHandle hFile ); + +/** Set the time scale of the movie (file). + * + * MP4SetTimeScale sets the time scale of the mp4 file. The time scale is + * in the number of clock ticks per second. Caveat: tracks may use the + * same time scale as the movie or may use their own time scale. + * + * @param hFile handle of file for operation. + * @param value desired timescale for the movie. + * + * @return On success, true. On failure, false. + */ +MP4V2_EXPORT +bool MP4SetTimeScale( MP4FileHandle hFile, uint32_t value ); + +/** Change the general timescale of file hFile. + * + * This function changes the general timescale of the file hFile + * to the new timescale value by recalculating all values that depend + * on the timescale in "moov.mvhd". + * + * If the timescale is already equal to value nothing is done. + * + * @param hFile handle of file to change. + * @param value the new timescale. + */ +MP4V2_EXPORT +void MP4ChangeMovieTimeScale( MP4FileHandle hFile, uint32_t value ); + +MP4V2_EXPORT +uint8_t MP4GetODProfileLevel( MP4FileHandle hFile ); + +MP4V2_EXPORT +bool MP4SetODProfileLevel( MP4FileHandle hFile, uint8_t value ); + +MP4V2_EXPORT +uint8_t MP4GetSceneProfileLevel( MP4FileHandle hFile ); + +MP4V2_EXPORT +bool MP4SetSceneProfileLevel( MP4FileHandle hFile, uint8_t value ); + +MP4V2_EXPORT +uint8_t MP4GetVideoProfileLevel( + MP4FileHandle hFile, + MP4TrackId trackId DEFAULT(MP4_INVALID_TRACK_ID) ); + +MP4V2_EXPORT +void MP4SetVideoProfileLevel( MP4FileHandle hFile, uint8_t value ); + +MP4V2_EXPORT +uint8_t MP4GetAudioProfileLevel( MP4FileHandle hFile ); + +MP4V2_EXPORT +void MP4SetAudioProfileLevel( MP4FileHandle hFile, uint8_t value ); + +MP4V2_EXPORT +uint8_t MP4GetGraphicsProfileLevel( MP4FileHandle hFile ); + +MP4V2_EXPORT +bool MP4SetGraphicsProfileLevel( MP4FileHandle hFile, uint8_t value ); + +/** @} ***********************************************************************/ + +#endif /* MP4V2_FILE_PROP_H */ diff --git a/mp4v2/mp4v2/general.h b/mp4v2/mp4v2/general.h new file mode 100644 index 0000000..48846bc --- /dev/null +++ b/mp4v2/mp4v2/general.h @@ -0,0 +1,496 @@ +#ifndef MP4V2_GENERAL_H +#define MP4V2_GENERAL_H + +/**************************************************************************//** + * + * @defgroup mp4_general MP4v2 General + * @{ + * + *****************************************************************************/ + +/* MP4 API types */ +typedef void* MP4FileHandle; +typedef uint32_t MP4TrackId; +typedef uint32_t MP4SampleId; +typedef uint64_t MP4Timestamp; +typedef uint64_t MP4Duration; +typedef uint32_t MP4EditId; + +typedef enum { + MP4_LOG_NONE = 0, + MP4_LOG_ERROR = 1, + MP4_LOG_WARNING = 2, + MP4_LOG_INFO = 3, + MP4_LOG_VERBOSE1 = 4, + MP4_LOG_VERBOSE2 = 5, + MP4_LOG_VERBOSE3 = 6, + MP4_LOG_VERBOSE4 = 7 +} MP4LogLevel; + +/*****************************************************************************/ + +typedef void (*MP4LogCallback)( + MP4LogLevel loglevel, + const char* fmt, + va_list ap ); + +/*****************************************************************************/ + +/** Encryption function pointer. + * + * @see MP4EncAndCopySample(). + * @see MP4EncAndCopyTrack(). + */ +typedef uint32_t (*encryptFunc_t)( uint32_t, uint32_t, uint8_t*, uint32_t*, uint8_t** ); + +/*****************************************************************************/ + +#define MP4_INVALID_FILE_HANDLE ((MP4FileHandle)NULL) /**< Constant: invalid MP4FileHandle. */ +#define MP4_INVALID_TRACK_ID ((MP4TrackId)0) /**< Constant: invalid MP4TrackId. */ +#define MP4_INVALID_SAMPLE_ID ((MP4SampleId)0) /**< Constant: invalid MP4SampleId. */ +#define MP4_INVALID_TIMESTAMP ((MP4Timestamp)-1) /**< Constant: invalid MP4Timestamp. */ +#define MP4_INVALID_DURATION ((MP4Duration)-1) /**< Constant: invalid MP4Duration. */ +#define MP4_INVALID_EDIT_ID ((MP4EditId)0) /**< Constant: invalid MP4EditId. */ + +/* Macros to test for API type validity */ +#define MP4_IS_VALID_FILE_HANDLE(x) ((x) != MP4_INVALID_FILE_HANDLE) +#define MP4_IS_VALID_TRACK_ID(x) ((x) != MP4_INVALID_TRACK_ID) +#define MP4_IS_VALID_SAMPLE_ID(x) ((x) != MP4_INVALID_SAMPLE_ID) +#define MP4_IS_VALID_TIMESTAMP(x) ((x) != MP4_INVALID_TIMESTAMP) +#define MP4_IS_VALID_DURATION(x) ((x) != MP4_INVALID_DURATION) +#define MP4_IS_VALID_EDIT_ID(x) ((x) != MP4_INVALID_EDIT_ID) + +/* + * MP4 Known track type names - e.g. MP4GetNumberOfTracks(type) + * + * Note this first group of track types should be created + * via the MP4AddTrack() functions, and not MP4AddTrack(type) + */ +#define MP4_OD_TRACK_TYPE "odsm" /**< Constant: OD track. */ +#define MP4_SCENE_TRACK_TYPE "sdsm" /**< Constant: scene track. */ +#define MP4_AUDIO_TRACK_TYPE "soun" /**< Constant: audio track. */ +#define MP4_VIDEO_TRACK_TYPE "vide" /**< Constant: video track. */ +#define MP4_HINT_TRACK_TYPE "hint" /**< Constant: hint track. */ +#define MP4_CNTL_TRACK_TYPE "cntl" /**< Constant: control track. */ +#define MP4_TEXT_TRACK_TYPE "text" /**< Constant: text track. */ +#define MP4_SUBTITLE_TRACK_TYPE "sbtl" /**< Constant: subtitle track. */ +#define MP4_CC_TRACK_TYPE "clcp" /**< Constant: closed captions track. */ +#define MP4_SUBPIC_TRACK_TYPE "subp" /**< Constant: subpic track. */ +/* + * This second set of track types should be created + * via MP4AddSystemsTrack(type) + */ +#define MP4_CLOCK_TRACK_TYPE "crsm" /**< Constant: clock track. */ +#define MP4_MPEG7_TRACK_TYPE "m7sm" /**< Constant: mpeg7 track. */ +#define MP4_OCI_TRACK_TYPE "ocsm" /**< Constant: OCI track. */ +#define MP4_IPMP_TRACK_TYPE "ipsm" /**< Constant: IPMP track. */ +#define MP4_MPEGJ_TRACK_TYPE "mjsm" /**< Constant: MPEGJ track. */ + +#define MP4_IS_VIDEO_TRACK_TYPE(type) \ + (!strcasecmp(type, MP4_VIDEO_TRACK_TYPE)) + +#define MP4_IS_AUDIO_TRACK_TYPE(type) \ + (!strcasecmp(type, MP4_AUDIO_TRACK_TYPE)) + +#define MP4_IS_CNTL_TRACK_TYPE(type) \ + (!strcasecmp(type, MP4_CNTL_TRACK_TYPE)) + +#define MP4_IS_OD_TRACK_TYPE(type) \ + (!strcasecmp(type, MP4_OD_TRACK_TYPE)) + +#define MP4_IS_SCENE_TRACK_TYPE(type) \ + (!strcasecmp(type, MP4_SCENE_TRACK_TYPE)) + +#define MP4_IS_HINT_TRACK_TYPE(type) \ + (!strcasecmp(type, MP4_HINT_TRACK_TYPE)) + +#define MP4_IS_SYSTEMS_TRACK_TYPE(type) \ + (!strcasecmp(type, MP4_CLOCK_TRACK_TYPE) \ + || !strcasecmp(type, MP4_MPEG7_TRACK_TYPE) \ + || !strcasecmp(type, MP4_OCI_TRACK_TYPE) \ + || !strcasecmp(type, MP4_IPMP_TRACK_TYPE) \ + || !strcasecmp(type, MP4_MPEGJ_TRACK_TYPE)) + +/* MP4 Audio track types - see MP4AddAudioTrack()*/ +#define MP4_INVALID_AUDIO_TYPE 0x00 +#define MP4_MPEG1_AUDIO_TYPE 0x6B +#define MP4_MPEG2_AUDIO_TYPE 0x69 +#define MP4_MP3_AUDIO_TYPE MP4_MPEG2_AUDIO_TYPE +#define MP4_MPEG2_AAC_MAIN_AUDIO_TYPE 0x66 +#define MP4_MPEG2_AAC_LC_AUDIO_TYPE 0x67 +#define MP4_MPEG2_AAC_SSR_AUDIO_TYPE 0x68 +#define MP4_MPEG2_AAC_AUDIO_TYPE MP4_MPEG2_AAC_MAIN_AUDIO_TYPE +#define MP4_MPEG4_AUDIO_TYPE 0x40 +#define MP4_PRIVATE_AUDIO_TYPE 0xC0 +#define MP4_PCM16_LITTLE_ENDIAN_AUDIO_TYPE 0xE0 /* a private definition */ +#define MP4_VORBIS_AUDIO_TYPE 0xE1 /* a private definition */ +#define MP4_AC3_AUDIO_TYPE 0xE2 /* a private definition */ +#define MP4_ALAW_AUDIO_TYPE 0xE3 /* a private definition */ +#define MP4_ULAW_AUDIO_TYPE 0xE4 /* a private definition */ +#define MP4_G723_AUDIO_TYPE 0xE5 /* a private definition */ +#define MP4_PCM16_BIG_ENDIAN_AUDIO_TYPE 0xE6 /* a private definition */ + +/* MP4 MPEG-4 Audio types from 14496-3 Table 1.5.1 */ +#define MP4_MPEG4_INVALID_AUDIO_TYPE 0 +#define MP4_MPEG4_AAC_MAIN_AUDIO_TYPE 1 +#define MP4_MPEG4_AAC_LC_AUDIO_TYPE 2 +#define MP4_MPEG4_AAC_SSR_AUDIO_TYPE 3 +#define MP4_MPEG4_AAC_LTP_AUDIO_TYPE 4 +#define MP4_MPEG4_AAC_HE_AUDIO_TYPE 5 +#define MP4_MPEG4_AAC_SCALABLE_AUDIO_TYPE 6 +#define MP4_MPEG4_CELP_AUDIO_TYPE 8 +#define MP4_MPEG4_HVXC_AUDIO_TYPE 9 +#define MP4_MPEG4_TTSI_AUDIO_TYPE 12 +#define MP4_MPEG4_MAIN_SYNTHETIC_AUDIO_TYPE 13 +#define MP4_MPEG4_WAVETABLE_AUDIO_TYPE 14 +#define MP4_MPEG4_MIDI_AUDIO_TYPE 15 +#define MP4_MPEG4_ALGORITHMIC_FX_AUDIO_TYPE 16 +#define MP4_MPEG4_ALS_AUDIO_TYPE 31 +#define MP4_MPEG4_LAYER1_AUDIO_TYPE 32 +#define MP4_MPEG4_LAYER2_AUDIO_TYPE 33 +#define MP4_MPEG4_LAYER3_AUDIO_TYPE 34 +#define MP4_MPEG4_SLS_AUDIO_TYPE 35 + +/* MP4 Audio type utilities following common usage */ +#define MP4_IS_MP3_AUDIO_TYPE(type) \ + ((type) == MP4_MPEG1_AUDIO_TYPE || (type) == MP4_MPEG2_AUDIO_TYPE) + +#define MP4_IS_MPEG2_AAC_AUDIO_TYPE(type) \ + (((type) >= MP4_MPEG2_AAC_MAIN_AUDIO_TYPE \ + && (type) <= MP4_MPEG2_AAC_SSR_AUDIO_TYPE)) + +#define MP4_IS_MPEG4_AAC_AUDIO_TYPE(mpeg4Type) \ + (((mpeg4Type) >= MP4_MPEG4_AAC_MAIN_AUDIO_TYPE \ + && (mpeg4Type) <= MP4_MPEG4_AAC_HE_AUDIO_TYPE) \ + || (mpeg4Type) == MP4_MPEG4_AAC_SCALABLE_AUDIO_TYPE \ + || (mpeg4Type) == 17) + +#define MP4_IS_AAC_AUDIO_TYPE(type) \ + (MP4_IS_MPEG2_AAC_AUDIO_TYPE(type) \ + || (type) == MP4_MPEG4_AUDIO_TYPE) + +/* MP4 Video track types - see MP4AddVideoTrack() */ +#define MP4_INVALID_VIDEO_TYPE 0x00 +#define MP4_MPEG1_VIDEO_TYPE 0x6A +#define MP4_MPEG2_SIMPLE_VIDEO_TYPE 0x60 +#define MP4_MPEG2_MAIN_VIDEO_TYPE 0x61 +#define MP4_MPEG2_SNR_VIDEO_TYPE 0x62 +#define MP4_MPEG2_SPATIAL_VIDEO_TYPE 0x63 +#define MP4_MPEG2_HIGH_VIDEO_TYPE 0x64 +#define MP4_MPEG2_442_VIDEO_TYPE 0x65 +#define MP4_MPEG2_VIDEO_TYPE MP4_MPEG2_MAIN_VIDEO_TYPE +#define MP4_MPEG4_VIDEO_TYPE 0x20 +#define MP4_JPEG_VIDEO_TYPE 0x6C +#define MP4_PRIVATE_VIDEO_TYPE 0xD0 +#define MP4_YUV12_VIDEO_TYPE 0xF0 /* a private definition */ +#define MP4_H263_VIDEO_TYPE 0xF2 /* a private definition */ +#define MP4_H261_VIDEO_TYPE 0xF3 /* a private definition */ + +/* MP4 Video type utilities */ +#define MP4_IS_MPEG1_VIDEO_TYPE(type) \ + ((type) == MP4_MPEG1_VIDEO_TYPE) + +#define MP4_IS_MPEG2_VIDEO_TYPE(type) \ + (((type) >= MP4_MPEG2_SIMPLE_VIDEO_TYPE \ + && (type) <= MP4_MPEG2_442_VIDEO_TYPE) \ + || MP4_IS_MPEG1_VIDEO_TYPE(type)) + +#define MP4_IS_MPEG4_VIDEO_TYPE(type) \ + ((type) == MP4_MPEG4_VIDEO_TYPE) + +/* Mpeg4 Visual Profile Defines - ISO/IEC 14496-2:2001/Amd.2:2002(E) */ +#define MPEG4_SP_L1 (0x1) +#define MPEG4_SP_L2 (0x2) +#define MPEG4_SP_L3 (0x3) +#define MPEG4_SP_L0 (0x8) +#define MPEG4_SSP_L1 (0x11) +#define MPEG4_SSP_L2 (0x12) +#define MPEG4_CP_L1 (0x21) +#define MPEG4_CP_L2 (0x22) +#define MPEG4_MP_L2 (0x32) +#define MPEG4_MP_L3 (0x33) +#define MPEG4_MP_L4 (0x34) +#define MPEG4_NBP_L2 (0x42) +#define MPEG4_STP_L1 (0x51) +#define MPEG4_SFAP_L1 (0x61) +#define MPEG4_SFAP_L2 (0x62) +#define MPEG4_SFBAP_L1 (0x63) +#define MPEG4_SFBAP_L2 (0x64) +#define MPEG4_BATP_L1 (0x71) +#define MPEG4_BATP_L2 (0x72) +#define MPEG4_HP_L1 (0x81) +#define MPEG4_HP_L2 (0x82) +#define MPEG4_ARTSP_L1 (0x91) +#define MPEG4_ARTSP_L2 (0x92) +#define MPEG4_ARTSP_L3 (0x93) +#define MPEG4_ARTSP_L4 (0x94) +#define MPEG4_CSP_L1 (0xa1) +#define MPEG4_CSP_L2 (0xa2) +#define MPEG4_CSP_L3 (0xa3) +#define MPEG4_ACEP_L1 (0xb1) +#define MPEG4_ACEP_L2 (0xb2) +#define MPEG4_ACEP_L3 (0xb3) +#define MPEG4_ACEP_L4 (0xb4) +#define MPEG4_ACP_L1 (0xc1) +#define MPEG4_ACP_L2 (0xc2) +#define MPEG4_AST_L1 (0xd1) +#define MPEG4_AST_L2 (0xd2) +#define MPEG4_AST_L3 (0xd3) +#define MPEG4_S_STUDIO_P_L1 (0xe1) +#define MPEG4_S_STUDIO_P_L2 (0xe2) +#define MPEG4_S_STUDIO_P_L3 (0xe3) +#define MPEG4_S_STUDIO_P_L4 (0xe4) +#define MPEG4_C_STUDIO_P_L1 (0xe5) +#define MPEG4_C_STUDIO_P_L2 (0xe6) +#define MPEG4_C_STUDIO_P_L3 (0xe7) +#define MPEG4_C_STUDIO_P_L4 (0xe8) +#define MPEG4_ASP_L0 (0xF0) +#define MPEG4_ASP_L1 (0xF1) +#define MPEG4_ASP_L2 (0xF2) +#define MPEG4_ASP_L3 (0xF3) +#define MPEG4_ASP_L4 (0xF4) +#define MPEG4_ASP_L5 (0xF5) +#define MPEG4_ASP_L3B (0xF7) +#define MPEG4_FGSP_L0 (0xf8) +#define MPEG4_FGSP_L1 (0xf9) +#define MPEG4_FGSP_L2 (0xfa) +#define MPEG4_FGSP_L3 (0xfb) +#define MPEG4_FGSP_L4 (0xfc) +#define MPEG4_FGSP_L5 (0xfd) + +/*****************************************************************************/ + +/* 3GP specific utilities */ + +MP4V2_EXPORT +bool MP4Make3GPCompliant( + const char* fileName, + char* majorBrand DEFAULT(0), + uint32_t minorVersion DEFAULT(0), + char** supportedBrands DEFAULT(NULL), + uint32_t supportedBrandsCount DEFAULT(0), + bool deleteIodsAtom DEFAULT(true) ); + +/* NOTE this section of functionality has not yet been fully tested */ + +MP4V2_EXPORT +MP4EditId MP4AddTrackEdit( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4EditId editId DEFAULT(MP4_INVALID_EDIT_ID), + MP4Timestamp startTime DEFAULT(0), + MP4Duration duration DEFAULT(0), + bool dwell DEFAULT(false) ); + +MP4V2_EXPORT +bool MP4DeleteTrackEdit( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4EditId editId ); + +MP4V2_EXPORT +uint32_t MP4GetTrackNumberOfEdits( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +MP4Timestamp MP4GetTrackEditStart( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4EditId editId ); + +MP4V2_EXPORT +MP4Duration MP4GetTrackEditTotalDuration( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4EditId editId DEFAULT(MP4_INVALID_EDIT_ID) ); + +MP4V2_EXPORT +MP4Timestamp MP4GetTrackEditMediaStart( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4EditId editId ); + +MP4V2_EXPORT +bool MP4SetTrackEditMediaStart( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4EditId editId, + MP4Timestamp startTime ); + +MP4V2_EXPORT +MP4Duration MP4GetTrackEditDuration( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4EditId editId ); + +MP4V2_EXPORT +bool MP4SetTrackEditDuration( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4EditId editId, + MP4Duration duration ); + +MP4V2_EXPORT +int8_t MP4GetTrackEditDwell( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4EditId editId ); + +MP4V2_EXPORT +bool MP4SetTrackEditDwell( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4EditId editId, + bool dwell ); + +MP4V2_EXPORT +bool MP4ReadSampleFromEditTime( + /* input parameters */ + MP4FileHandle hFile, + MP4TrackId trackId, + MP4Timestamp when, + /* input/output parameters */ + uint8_t** ppBytes, + uint32_t* pNumBytes, + /* output parameters */ + MP4Timestamp* pStartTime DEFAULT(NULL), + MP4Duration* pDuration DEFAULT(NULL), + MP4Duration* pRenderingOffset DEFAULT(NULL), + bool* pIsSyncSample DEFAULT(NULL) ); + +MP4V2_EXPORT +MP4SampleId MP4GetSampleIdFromEditTime( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4Timestamp when, + MP4Timestamp* pStartTime DEFAULT(NULL), + MP4Duration* pDuration DEFAULT(NULL) ); + +/* time conversion utilties */ + +/* predefined values for timeScale parameter below */ +#define MP4_SECONDS_TIME_SCALE 1 +#define MP4_MILLISECONDS_TIME_SCALE 1000 +#define MP4_MICROSECONDS_TIME_SCALE 1000000 +#define MP4_NANOSECONDS_TIME_SCALE 1000000000 + +#define MP4_SECS_TIME_SCALE MP4_SECONDS_TIME_SCALE +#define MP4_MSECS_TIME_SCALE MP4_MILLISECONDS_TIME_SCALE +#define MP4_USECS_TIME_SCALE MP4_MICROSECONDS_TIME_SCALE +#define MP4_NSECS_TIME_SCALE MP4_NANOSECONDS_TIME_SCALE + +MP4V2_EXPORT +uint64_t MP4ConvertFromMovieDuration( + MP4FileHandle hFile, + MP4Duration duration, + uint32_t timeScale ); + +MP4V2_EXPORT +uint64_t MP4ConvertFromTrackTimestamp( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4Timestamp timeStamp, + uint32_t timeScale ); + +MP4V2_EXPORT +MP4Timestamp MP4ConvertToTrackTimestamp( + MP4FileHandle hFile, + MP4TrackId trackId, + uint64_t timeStamp, + uint32_t timeScale ); + +/** Convert duration from track time scale to an arbitrary time scale. + * + * MP4ConvertFromTrackDuration converts a duration such as a sample duration + * from the track time scale to another time scale. This can be used by a + * player application to map all track samples to a common time scale. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param duration value to be converted. + * @param timeScale time scale in ticks per second. + * + * @return On success, the duration in arbitrary time scale units. + * On error, 0. + * + * @see MP4GetSampleDuration(). + * @see MP4ConvertToTrackDuration(). + */ +MP4V2_EXPORT +uint64_t MP4ConvertFromTrackDuration( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4Duration duration, + uint32_t timeScale ); + +/** Convert duration from arbitrary time scale to track time scale. + * + * MP4ConvertToTrackDuration converts a duration such as a sample duration + * from the specified time scale to the track time scale. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param duration value to be converted. + * @param timeScale time scale in ticks per second. + * + * @return On success, the duration in track time scale units. + * On error, #MP4_INVALID_DURATION. + * + * @see MP4ConvertFromTrackDuration(). + */ +MP4V2_EXPORT +MP4Duration MP4ConvertToTrackDuration( + MP4FileHandle hFile, + MP4TrackId trackId, + uint64_t duration, + uint32_t timeScale ); + +MP4V2_EXPORT +char* MP4BinaryToBase16( + const uint8_t* pData, + uint32_t dataSize ); + +MP4V2_EXPORT +char* MP4BinaryToBase64( + const uint8_t* pData, + uint32_t dataSize ); + +MP4V2_EXPORT +uint8_t* Base64ToBinary( + const char* pData, + uint32_t decodeSize, + uint32_t* pDataSize ); + +MP4V2_EXPORT +void MP4Free( + void* p ); + +/** Set the function to call in place of default logging behavior + * + * @param cb_func the function to call + */ +MP4V2_EXPORT +void MP4SetLogCallback( + MP4LogCallback cb_func ); +/** @} ***********************************************************************/ + +/** + * Accessor for the maximum level for diagnostic information + * + * @return the maximum level for diagnostic information + * + * @see MP4LogSetLevel() for further details. + */ +MP4V2_EXPORT +MP4LogLevel MP4LogGetLevel( void ); + +/** + * Set the maximum level for diagnostic information + * + * @param verbosity the level to set + */ +MP4V2_EXPORT +void MP4LogSetLevel( MP4LogLevel verbosity ); + +#endif /* MP4V2_GENERAL_H */ diff --git a/mp4v2/mp4v2/isma.h b/mp4v2/mp4v2/isma.h new file mode 100644 index 0000000..074a06e --- /dev/null +++ b/mp4v2/mp4v2/isma.h @@ -0,0 +1,96 @@ +#ifndef MP4V2_ISMA_H +#define MP4V2_ISMA_H + +/**************************************************************************//** + * + * @defgroup mp4_isma MP4v2 ISMA (Internet Streaming Media Alliance) + * @{ + * + *****************************************************************************/ + +/** something */ +typedef struct mp4v2_ismacryp_session_params { + uint32_t scheme_type; + uint16_t scheme_version; + uint8_t key_ind_len; + uint8_t iv_len; + uint8_t selective_enc; + const char* kms_uri; +} mp4v2_ismacrypParams; + +/* + * API to initialize ismacryp properties to sensible defaults + * if input param is null then mallocs a params struct + */ + +MP4V2_EXPORT +mp4v2_ismacrypParams* MP4DefaultISMACrypParams( mp4v2_ismacrypParams* ptr ); + +MP4V2_EXPORT +MP4TrackId MP4AddEncAudioTrack( + MP4FileHandle hFile, + uint32_t timeScale, + MP4Duration sampleDuration, + mp4v2_ismacrypParams* icPp, + uint8_t audioType DEFAULT(MP4_MPEG4_AUDIO_TYPE) ); + +MP4V2_EXPORT +MP4TrackId MP4AddEncVideoTrack( + MP4FileHandle hFile, + uint32_t timeScale, + MP4Duration sampleDuration, + uint16_t width, + uint16_t height, + mp4v2_ismacrypParams* icPp, + uint8_t videoType DEFAULT(MP4_MPEG4_VIDEO_TYPE), + const char* oFormat DEFAULT(NULL) ); + +MP4V2_EXPORT +MP4TrackId MP4AddEncH264VideoTrack( + MP4FileHandle dstFile, + uint32_t timeScale, + MP4Duration sampleDuration, + uint16_t width, + uint16_t height, + MP4FileHandle srcFile, + MP4TrackId srcTrackId, + mp4v2_ismacrypParams* icPp ); + +MP4V2_EXPORT +MP4TrackId MP4EncAndCloneTrack( + MP4FileHandle srcFile, + MP4TrackId srcTrackId, + mp4v2_ismacrypParams* icPp, + MP4FileHandle dstFile DEFAULT(MP4_INVALID_FILE_HANDLE), + MP4TrackId dstHintTrackReferenceTrack DEFAULT(MP4_INVALID_TRACK_ID) ); + +MP4V2_EXPORT +MP4TrackId MP4EncAndCopyTrack( + MP4FileHandle srcFile, + MP4TrackId srcTrackId, + mp4v2_ismacrypParams* icPp, + encryptFunc_t encfcnp, + uint32_t encfcnparam1, + MP4FileHandle dstFile DEFAULT(MP4_INVALID_FILE_HANDLE), + bool applyEdits DEFAULT(false), + MP4TrackId dstHintTrackReferenceTrack DEFAULT(MP4_INVALID_TRACK_ID) ); + +MP4V2_EXPORT +bool MP4MakeIsmaCompliant( + const char* fileName, + bool addIsmaComplianceSdp DEFAULT(true) ); + +MP4V2_EXPORT +char* MP4MakeIsmaSdpIod( + uint8_t videoProfile, + uint32_t videoBitrate, + uint8_t* videoConfig, + uint32_t videoConfigLength, + uint8_t audioProfile, + uint32_t audioBitrate, + uint8_t* audioConfig, + uint32_t audioConfigLength ); + +/** @} ***********************************************************************/ + +#endif /* MP4V2_ISMA_H */ diff --git a/mp4v2/mp4v2/itmf_generic.h b/mp4v2/mp4v2/itmf_generic.h new file mode 100644 index 0000000..b780b1e --- /dev/null +++ b/mp4v2/mp4v2/itmf_generic.h @@ -0,0 +1,207 @@ +#ifndef MP4V2_ITMF_GENERIC_H +#define MP4V2_ITMF_GENERIC_H + +/**************************************************************************//** + * + * @defgroup mp4_itmf_generic MP4v2 iTMF (iTunes Metadata Format) Generic + * @{ + * + * This is a low-level API used to manage iTMF metadata. + * + * It provides support for virtually any kind of iTMF metadata item, + * including meaning atoms, sometimes referred to as reverse-DNS meanings. + * Structures are directly modified; ie: there are no fuctions which + * modify values for you. There is little type-safety, logic checks, or + * specifications compliance checks. For these reasons it is recommended + * to use iTMF Tags API when possible. + * + * At the heart of this API is an #MP4ItmfItem which corresponds to an + * iTMF metadata item atom. The item, and any recursive data structures + * contained within require manual memory management. The general + * rule to follow is that you must always check/free a ptr if you intend + * to resize data. In cases where you know the existing data size is + * exactly what is needed, you may overwrite the buffer contents. + * + * Each item always has at least 1 data elements which corresponds to + * a data atom. Additionally, each item has optional mean and + * name values which correspond to mean and name atoms. + * + * Each #MP4ItmfItem has a list of #MP4ItmfData. Similarily, care must + * be taken to manage memory with one key difference; these structures + * also have a valueSize field. If value is NULL then set valueSize=0. + * Otherwise, set valueSize to the size (in bytes) of value buffer. + * + * In rare cases where the number of data elements in a single item + * is > 1, the user must manually free/alloc/copy the elements + * buffer and update size accordingly. + * + * The mp4 file structure is modified only when MP4AddItem(), + * MP4SetItem() and MP4RemoveItem() are used. Simply free'ing + * the item list does not modify the mp4 file. + * + * iTMF Generic read workflow: + * + * @li MP4ItmfGetItems() + * @li inspect each item... + * @li MP4ItmfItemListFree() + * + * iTMF Generic read/modify/remove workflow: + * + * @li MP4ItmfGetItems() + * @li inspect/modify item... + * @li MP4ItmfSetItem() each modified item... + * @li MP4ItmfRemoveItem()... + * @li MP4ItmfItemListFree() + * + * iTMF Generic add workflow: + * + * @li MP4ItmfItemAlloc() + * @li MP4ItmfAddItem() + * @li MP4ItmfItemFree() + * + * @par Warning: + * Care must be taken when using multiple mechanisms to modify an open mp4 + * file as it is not thread-safe, nor does it permit overlapping different + * API workflows which have a begin/end to their workflow. That is to say + * do not interleave an iTMF Generic workflow with an iTMF Tags workflow. + * + *****************************************************************************/ + +/** Basic types of value data as enumerated in spec. */ +typedef enum MP4ItmfBasicType_e +{ + MP4_ITMF_BT_IMPLICIT = 0, /**< for use with tags for which no type needs to be indicated */ + MP4_ITMF_BT_UTF8 = 1, /**< without any count or null terminator */ + MP4_ITMF_BT_UTF16 = 2, /**< also known as UTF-16BE */ + MP4_ITMF_BT_SJIS = 3, /**< deprecated unless it is needed for special Japanese characters */ + MP4_ITMF_BT_HTML = 6, /**< the HTML file header specifies which HTML version */ + MP4_ITMF_BT_XML = 7, /**< the XML header must identify the DTD or schemas */ + MP4_ITMF_BT_UUID = 8, /**< also known as GUID; stored as 16 bytes in binary (valid as an ID) */ + MP4_ITMF_BT_ISRC = 9, /**< stored as UTF-8 text (valid as an ID) */ + MP4_ITMF_BT_MI3P = 10, /**< stored as UTF-8 text (valid as an ID) */ + MP4_ITMF_BT_GIF = 12, /**< (deprecated) a GIF image */ + MP4_ITMF_BT_JPEG = 13, /**< a JPEG image */ + MP4_ITMF_BT_PNG = 14, /**< a PNG image */ + MP4_ITMF_BT_URL = 15, /**< absolute, in UTF-8 characters */ + MP4_ITMF_BT_DURATION = 16, /**< in milliseconds, 32-bit integer */ + MP4_ITMF_BT_DATETIME = 17, /**< in UTC, counting seconds since midnight, January 1, 1904; 32 or 64-bits */ + MP4_ITMF_BT_GENRES = 18, /**< a list of enumerated values */ + MP4_ITMF_BT_INTEGER = 21, /**< a signed big-endian integer with length one of { 1,2,3,4,8 } bytes */ + MP4_ITMF_BT_RIAA_PA = 24, /**< RIAA parental advisory; { -1=no, 1=yes, 0=unspecified }, 8-bit ingteger */ + MP4_ITMF_BT_UPC = 25, /**< Universal Product Code, in text UTF-8 format (valid as an ID) */ + MP4_ITMF_BT_BMP = 27, /**< Windows bitmap image */ + + MP4_ITMF_BT_UNDEFINED = 255 /**< undefined */ +} MP4ItmfBasicType; + +/** Data structure. + * Models an iTMF data atom contained in an iTMF metadata item atom. + */ +typedef struct MP4ItmfData_s +{ + uint8_t typeSetIdentifier; /**< always zero. */ + MP4ItmfBasicType typeCode; /**< iTMF basic type. */ + uint32_t locale; /**< always zero. */ + uint8_t* value; /**< may be NULL. */ + uint32_t valueSize; /**< value size in bytes. */ +} MP4ItmfData; + +/** List of data. */ +typedef struct MP4ItmfDataList_s +{ + MP4ItmfData* elements; /**< flat array. NULL when size is zero. */ + uint32_t size; /**< number of elements. */ +} MP4ItmfDataList; + +/** Item structure. + * Models an iTMF metadata item atom contained in an ilst atom. + */ +typedef struct MP4ItmfItem_s +{ + void* __handle; /**< internal use only. */ + + char* code; /**< four-char code identifing atom type. NULL-terminated. */ + char* mean; /**< may be NULL. UTF-8 meaning. NULL-terminated. */ + char* name; /**< may be NULL. UTF-8 name. NULL-terminated. */ + MP4ItmfDataList dataList; /**< list of data. can be zero length. */ +} MP4ItmfItem; + +/** List of items. */ +typedef struct MP4ItmfItemList_s +{ + MP4ItmfItem* elements; /**< flat array. NULL when size is zero. */ + uint32_t size; /**< number of elements. */ +} MP4ItmfItemList; + +/** Allocate an item on the heap. + * @param code four-char code identifying atom type. NULL-terminated. + * @param numData number of data elements to allocate. Must be >= 1. + * @return newly allocated item. + */ +MP4V2_EXPORT MP4ItmfItem* +MP4ItmfItemAlloc( const char* code, uint32_t numData ); + +/** Free an item (deep free). + * @param item to be free'd. + */ +MP4V2_EXPORT void +MP4ItmfItemFree( MP4ItmfItem* item ); + +/** Free an item list (deep free). + * @param itemList to be free'd. + */ +MP4V2_EXPORT void +MP4ItmfItemListFree( MP4ItmfItemList* itemList ); + +/** Get list of all items from file. + * @param hFile handle of file to operate on. + * @return On succes, list of items, which must be free'd. On failure, NULL. + */ +MP4V2_EXPORT MP4ItmfItemList* +MP4ItmfGetItems( MP4FileHandle hFile ); + +/** Get list of items by code from file. + * @param hFile handle of file to operate on. + * @param code four-char code identifying atom type. NULL-terminated. + * @return On succes, list of items, which must be free'd. On failure, NULL. + */ +MP4V2_EXPORT MP4ItmfItemList* +MP4ItmfGetItemsByCode( MP4FileHandle hFile, const char* code ); + +/** Get list of items by meaning from file. + * Implicitly only returns atoms of code @b{----}. + * @param hFile handle of file to operate on. + * @param meaning UTF-8 meaning. NULL-terminated. + * @param name may be NULL. UTF-8 name. NULL-terminated. + * @return On succes, list of items, which must be free'd. On failure, NULL. + */ +MP4V2_EXPORT MP4ItmfItemList* +MP4ItmfGetItemsByMeaning( MP4FileHandle hFile, const char* meaning, const char* name ); + +/** Add an item to file. + * @param hFile handle of file to operate on. + * @param item object to add. + * @return true on success, false on failure. + */ +MP4V2_EXPORT bool +MP4ItmfAddItem( MP4FileHandle hFile, const MP4ItmfItem* item ); + +/** Overwrite an existing item in file. + * @param hFile handle of file to operate on. + * @param item object to overwrite. Must have a valid index obtained from prior get. + * @return true on success, false on failure. + */ +MP4V2_EXPORT bool +MP4ItmfSetItem( MP4FileHandle hFile, const MP4ItmfItem* item ); + +/** Remove an existing item from file. + * @param hFile handle of file to operate on. + * @param item object to remove. Must have a valid index obtained from prior get. + * @return true on success, false on failure. + */ +MP4V2_EXPORT bool +MP4ItmfRemoveItem( MP4FileHandle hFile, const MP4ItmfItem* item ); + +/** @} ***********************************************************************/ + +#endif /* MP4V2_ITMF_GENERIC_H */ diff --git a/mp4v2/mp4v2/itmf_tags.h b/mp4v2/mp4v2/itmf_tags.h new file mode 100644 index 0000000..80d53f5 --- /dev/null +++ b/mp4v2/mp4v2/itmf_tags.h @@ -0,0 +1,337 @@ +#ifndef MP4V2_ITMF_TAGS_H +#define MP4V2_ITMF_TAGS_H + +/**************************************************************************//** + * + * @defgroup mp4_itmf_tags MP4v2 iTMF (iTunes Metadata Format) Tags + * @{ + * + * This is a high-level API used to manage iTMF metadata. + * + * It provides more type-safety and simplified memory management as compared + * to iTMF Generic API. + * + * At the heart of this API is a read-only structure that holds all known + * items and their current values. The value is always a pointer which if + * NULL indicates its corresponding atom does not exist. Thus, one must + * always check if the pointer is non-NULL before attempting to extract + * its value. + * + * The structure may not be directly modified. Instead, set functions + * corresponding to each item are used to modify the backing-store of + * the read-only structure. Setting the value ptr to NULL will effectively + * remove it. Setting the value ptr to real data will immediately make a + * copy of the value in the backing-store and the read-only structure + * will correctly reflect the change. + * + * The hidden data cache memory is automatically managed. Thus the user need + * only guarantee the data is available during the lifetime of the set-function + * call. + * + * iTMF Tags read workflow: + * + * @li MP4TagsAlloc() + * @li MP4TagsFetch() + * @li inspect each tag of interest... + * @li MP4TagsStore() (if modified) + * @li MP4TagsFree() + * + * iTMF Tags read/modify/add/remove workflow: + * + * @li MP4TagsAlloc() + * @li MP4TagsFetch() + * @li inspect each tag of interest... + * @li MP4TagsSetName(), MP4TagsSetArtist()... + * @li MP4TagsStore() + * @li MP4TagsFree() + * + * @par Warning: + * Care must be taken when using multiple mechanisms to modify an open mp4 + * file as it is not thread-safe, nor does it permit overlapping different + * API workflows which have a begin/end to their workflow. That is to say + * do not interleave an iTMF Generic workflow with an iTMF Tags workflow. + * + *****************************************************************************/ + +/** Enumeration of possible MP4TagArtwork::type values. */ +typedef enum MP4TagArtworkType_e +{ + MP4_ART_UNDEFINED = 0, + MP4_ART_BMP = 1, + MP4_ART_GIF = 2, + MP4_ART_JPEG = 3, + MP4_ART_PNG = 4 +} MP4TagArtworkType; + +/** Data object representing a single piece of artwork. */ +typedef struct MP4TagArtwork_s +{ + void* data; /**< raw picture data */ + uint32_t size; /**< data size in bytes */ + MP4TagArtworkType type; /**< data type */ +} MP4TagArtwork; + +typedef struct MP4TagTrack_s +{ + uint16_t index; + uint16_t total; +} MP4TagTrack; + +typedef struct MP4TagDisk_s +{ + uint16_t index; + uint16_t total; +} MP4TagDisk; + +/** Tags convenience structure. + * + * This structure is used in the tags convenience API which allows for + * simplified retrieval and modification of the majority of known tags. + * + * This is a read-only structure and each tag is present if and only if the + * pointer is a non-NULL value. The actual data is backed by a hidden + * data cache which is only updated when the appropriate metadata set + * function is used, or if MP4TagsFetch() is invoked. Thus, if other API + * is used to manipulate relevent atom structure of the MP4 file, the user + * is responsible for re-fetching the data in this structure. + */ +typedef struct MP4Tags_s +{ + void* __handle; /* internal use only */ + + const char* name; + const char* artist; + const char* albumArtist; + const char* album; + const char* grouping; + const char* composer; + const char* comments; + const char* genre; + const uint16_t* genreType; + const char* releaseDate; + const MP4TagTrack* track; + const MP4TagDisk* disk; + const uint16_t* tempo; + const uint8_t* compilation; + + const char* trackSubTitle; + const char* songDescription; + const char* artDirector; + const char* arranger; + const char* lyricist; + const char* acknowledgement; + const char* conductor; + + const char* linearNotes; + const char* recordCompany; + const char* originalArtist; + const char* phonogramRights; + const char* producer; + const char* performer; + const char* publisher; + const char* soundEngineer; + const char* soloist; + const char* credits; + const char* thanks; + const char* onlineExtras; + const char* executiveProducer; + + const char* tvShow; + const char* tvNetwork; + const char* tvEpisodeID; + const uint32_t* tvSeason; + const uint32_t* tvEpisode; + + const char* description; + const char* longDescription; + const char* seriesDescription; + const char* lyrics; + + const char* sortName; + const char* sortArtist; + const char* sortAlbumArtist; + const char* sortAlbum; + const char* sortComposer; + const char* sortTVShow; + + const MP4TagArtwork* artwork; + uint32_t artworkCount; + + const char* copyright; + const char* encodingTool; + const char* encodedBy; + const char* purchaseDate; + + const uint8_t* itunesu; + const uint8_t* podcast; + const char* keywords; /* TODO: Needs testing */ + const char* category; + + const uint8_t* hdVideo; + const uint8_t* mediaType; + const uint8_t* contentRating; + const uint8_t* gapless; + + const char* iTunesAccount; + const uint8_t* iTunesAccountType; + const uint32_t* iTunesCountry; + const uint32_t* contentID; + const uint32_t* artistID; + const uint64_t* playlistID; + const uint32_t* genreID; + const uint32_t* composerID; + const char* xid; +} MP4Tags; + +/** Allocate tags convenience structure for reading and settings tags. + * + * This function allocates a new structure which represents a snapshot + * of all the tags therein, tracking if the tag is missing, + * or present and with value. It is the caller's responsibility to free + * the structure with MP4TagsFree(). + * + * @return structure with all tags missing. + */ +MP4V2_EXPORT +const MP4Tags* MP4TagsAlloc( void ); + +/** Fetch data from mp4 file and populate structure. + * + * The tags structure and its hidden data-cache is updated to + * reflect the actual tags values found in the hFile. + * + * @param tags structure to fetch (write) into. + * @param hFile handle of file to fetch data from. + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4TagsFetch( const MP4Tags* tags, MP4FileHandle hFile ); + +/** Store data to mp4 file from structure. + * + * The tags structure is pushed out to the mp4 file, + * adding tags if needed, removing tags if needed, and updating + * the values to modified tags. + * + * @param tags structure to store (read) from. + * @param hFile handle of file to store data to. + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4TagsStore( const MP4Tags* tags, MP4FileHandle hFile ); + +/** Free tags convenience structure. + * + * This function frees memory associated with the structure. + * + * @param tags structure to destroy. + */ +MP4V2_EXPORT +void MP4TagsFree( const MP4Tags* tags ); + +/** Accessor that indicates whether a tags structure + * contains any metadata + * + * @param tags the structure to inspect + * + * @param hasMetadata populated with false if @p tags + * contains no metadata, true if @p tags contains metadata + * + * @retval false error determining if @p tags contains + * metadata + * + * @retval true successfully determined if @p tags contains + * metadata + */ +MP4V2_EXPORT +bool MP4TagsHasMetadata ( const MP4Tags* tags, bool *hasMetadata ); + +MP4V2_EXPORT bool MP4TagsSetName ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetArtist ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetAlbumArtist ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetAlbum ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetGrouping ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetComposer ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetComments ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetGenre ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetGenreType ( const MP4Tags*, const uint16_t* ); +MP4V2_EXPORT bool MP4TagsSetReleaseDate ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetTrack ( const MP4Tags*, const MP4TagTrack* ); +MP4V2_EXPORT bool MP4TagsSetDisk ( const MP4Tags*, const MP4TagDisk* ); +MP4V2_EXPORT bool MP4TagsSetTempo ( const MP4Tags*, const uint16_t* ); +MP4V2_EXPORT bool MP4TagsSetCompilation ( const MP4Tags*, const uint8_t* ); + +MP4V2_EXPORT bool MP4TagsSetTrackSubTitle ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetSongDescription ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetArtDirector ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetArranger ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetLyricist ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetAcknowledgement ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetConductor ( const MP4Tags*, const char* ); + +MP4V2_EXPORT bool MP4TagsSetLinearNotes ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetRecordCompany ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetOriginalArtist ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetPhonogramRights ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetProducer ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetPerformer ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetPublisher ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetSoundEngineer ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetSoloist ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetCredits ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetThanks ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetOnlineExtras ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetExecutiveProducer ( const MP4Tags*, const char* ); + +MP4V2_EXPORT bool MP4TagsSetTVShow ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetTVNetwork ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetTVEpisodeID ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetTVSeason ( const MP4Tags*, const uint32_t* ); +MP4V2_EXPORT bool MP4TagsSetTVEpisode ( const MP4Tags*, const uint32_t* ); + +MP4V2_EXPORT bool MP4TagsSetDescription ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetLongDescription ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetSeriesDescription ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetLyrics ( const MP4Tags*, const char* ); + +MP4V2_EXPORT bool MP4TagsSetSortName ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetSortArtist ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetSortAlbumArtist ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetSortAlbum ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetSortComposer ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetSortTVShow ( const MP4Tags*, const char* ); + +MP4V2_EXPORT bool MP4TagsAddArtwork ( const MP4Tags*, MP4TagArtwork* ); +MP4V2_EXPORT bool MP4TagsSetArtwork ( const MP4Tags*, uint32_t, MP4TagArtwork* ); +MP4V2_EXPORT bool MP4TagsRemoveArtwork ( const MP4Tags*, uint32_t ); + +MP4V2_EXPORT bool MP4TagsSetCopyright ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetEncodingTool ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetEncodedBy ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetPurchaseDate ( const MP4Tags*, const char* ); + +MP4V2_EXPORT bool MP4TagsSetITunesU ( const MP4Tags*, const uint8_t* ); +MP4V2_EXPORT bool MP4TagsSetPodcast ( const MP4Tags*, const uint8_t* ); +MP4V2_EXPORT bool MP4TagsSetKeywords ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetCategory ( const MP4Tags*, const char* ); + +MP4V2_EXPORT bool MP4TagsSetHDVideo ( const MP4Tags*, const uint8_t* ); +MP4V2_EXPORT bool MP4TagsSetMediaType ( const MP4Tags*, const uint8_t* ); +MP4V2_EXPORT bool MP4TagsSetContentRating ( const MP4Tags*, const uint8_t* ); +MP4V2_EXPORT bool MP4TagsSetGapless ( const MP4Tags*, const uint8_t* ); + +MP4V2_EXPORT bool MP4TagsSetITunesAccount ( const MP4Tags*, const char* ); +MP4V2_EXPORT bool MP4TagsSetITunesAccountType ( const MP4Tags*, const uint8_t* ); +MP4V2_EXPORT bool MP4TagsSetITunesCountry ( const MP4Tags*, const uint32_t* ); +MP4V2_EXPORT bool MP4TagsSetContentID ( const MP4Tags*, const uint32_t* ); +MP4V2_EXPORT bool MP4TagsSetArtistID ( const MP4Tags*, const uint32_t* ); +MP4V2_EXPORT bool MP4TagsSetPlaylistID ( const MP4Tags*, const uint64_t* ); +MP4V2_EXPORT bool MP4TagsSetGenreID ( const MP4Tags*, const uint32_t* ); +MP4V2_EXPORT bool MP4TagsSetComposerID ( const MP4Tags*, const uint32_t* ); +MP4V2_EXPORT bool MP4TagsSetXID ( const MP4Tags*, const char* ); + +/** @} ***********************************************************************/ + +#endif /* MP4V2_ITMF_TAGS_H */ diff --git a/mp4v2/mp4v2/platform.h b/mp4v2/mp4v2/platform.h new file mode 100644 index 0000000..d400edf --- /dev/null +++ b/mp4v2/mp4v2/platform.h @@ -0,0 +1,95 @@ +#ifndef MP4V2_PLATFORM_H +#define MP4V2_PLATFORM_H + +/*****************************************************************************/ + +#include +#include +#include + +// Thanks, MSFT, for making C99 a total PITA. Declare this not to define any stdint stuff; this is useful +// if you're going to be using mp4v2 on windows with some other library that defines its own stdint. +// TODO msft has finally re-included stdint in vs2010, so maybe at some point in the future this won't be needed. +#ifndef MP4V2_NO_STDINT_DEFS + #if defined( _WIN32 ) && !defined( __MINGW32__ ) + typedef char int8_t; + typedef short int16_t; + typedef int int32_t; + typedef long long int64_t; + + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; + typedef unsigned long long uint64_t; + #else + #include + #endif +#endif + +#if defined( _WIN32 ) || defined( __MINGW32__ ) +# if defined( MP4V2_EXPORTS ) +# define MP4V2_EXPORT __declspec(dllexport) +# elif defined( MP4V2_USE_DLL_IMPORT ) || !defined( MP4V2_USE_STATIC_LIB ) +# define MP4V2_EXPORT __declspec(dllimport) +# else +# define MP4V2_EXPORT +# endif +#else +# define MP4V2_EXPORT __attribute__((visibility("default"))) +#endif + +#if defined( __GNUC__ ) +# define MP4V2_DEPRECATED __attribute__((deprecated)) +#else +# define MP4V2_DEPRECATED +#endif + +/****************************************************************************** + * + * TODO-KB: cleanup -- absolutely no need for a C-API to fuss with reserved + * C++ keywords. This will involve changing the public interface and current + * plan of action: + * + * typdef enum { + * mp4_false, + * mp4_true, + * } mp4_bool_t; + * + * followed by updating all public signatures and implementation. + */ + +#ifndef FALSE +#define FALSE 0 +#endif + +#ifndef TRUE +#define TRUE 1 +#endif + +#if !defined( __cplusplus ) +#ifndef bool +#if SIZEOF_BOOL == 8 +typedef uint64_t bool; +#else +#if SIZEOF_BOOL == 4 +typedef uint32_t bool; +#else +#if SIZEOF_BOOL == 2 +typedef uint16_t bool; +#else +typedef unsigned char bool; +#endif +#endif +#endif +#ifndef false +#define false FALSE +#endif +#ifndef true +#define true TRUE +#endif +#endif +#endif + +/*****************************************************************************/ + +#endif /* MP4V2_PLATFORM_H */ diff --git a/mp4v2/mp4v2/project.h b/mp4v2/mp4v2/project.h new file mode 100644 index 0000000..ad841a1 --- /dev/null +++ b/mp4v2/mp4v2/project.h @@ -0,0 +1,31 @@ +#ifndef MP4V2_PROJECT_H +#define MP4V2_PROJECT_H + +/*****************************************************************************/ + +#define MP4V2_PROJECT_name "MP4v2" +#define MP4V2_PROJECT_name_lower "mp4v2" +#define MP4V2_PROJECT_name_upper "MP4V2" +#define MP4V2_PROJECT_name_formal "MP4v2 trunk-r487" +#define MP4V2_PROJECT_url_website "http://code.google.com/p/mp4v2" +#define MP4V2_PROJECT_url_downloads "http://code.google.com/p/mp4v2/downloads/list" +#define MP4V2_PROJECT_url_discussion "http://groups.google.com/group/mp4v2" +#define MP4V2_PROJECT_irc "irc://irc.freenode.net/handbrake" +#define MP4V2_PROJECT_bugreport "" +#define MP4V2_PROJECT_version "trunk-r487" +#define MP4V2_PROJECT_version_hex 0x00020000 +#define MP4V2_PROJECT_version_major 2 +#define MP4V2_PROJECT_version_minor 0 +#define MP4V2_PROJECT_version_point 0 +#define MP4V2_PROJECT_repo_url "http://mp4v2.googlecode.com/svn/trunk" +#define MP4V2_PROJECT_repo_branch "trunk" +#define MP4V2_PROJECT_repo_root "http://mp4v2.googlecode.com/svn" +#define MP4V2_PROJECT_repo_uuid "6e6572fa-98a6-11dd-ad9f-f77439c74b79" +#define MP4V2_PROJECT_repo_rev 487 +#define MP4V2_PROJECT_repo_date "2011-10-19 20:03:14 +0200 (Wed, 19 Oct 2011)" +#define MP4V2_PROJECT_repo_type "developer" +#define MP4V2_PROJECT_build "Sat Aug 4 12:47:15 CEST 2012" + +/*****************************************************************************/ + +#endif /* MP4V2_PROJECT_H */ diff --git a/mp4v2/mp4v2/sample.h b/mp4v2/mp4v2/sample.h new file mode 100644 index 0000000..ba35a57 --- /dev/null +++ b/mp4v2/mp4v2/sample.h @@ -0,0 +1,557 @@ +#ifndef MP4V2_SAMPLE_H +#define MP4V2_SAMPLE_H + +/**************************************************************************//** + * + * @defgroup mp4_sample MP4v2 Sample + * @{ + * + *****************************************************************************/ + +/** Sample dependency types. + * + * Bit combinations 0x03, 0x30, 0xc0 are reserved. + */ +typedef enum MP4SampleDependencyType_e { + MP4_SDT_UNKNOWN = 0x00, /**< unknown */ + MP4_SDT_HAS_REDUNDANT_CODING = 0x01, /**< contains redundant coding */ + MP4_SDT_HAS_NO_REDUNDANT_CODING = 0x02, /**< does not contain redundant coding */ + MP4_SDT_HAS_DEPENDENTS = 0x04, /**< referenced by other samples */ + MP4_SDT_HAS_NO_DEPENDENTS = 0x08, /**< not referenced by other samples */ + MP4_SDT_IS_DEPENDENT = 0x10, /**< references other samples */ + MP4_SDT_IS_INDEPENDENT = 0x20, /**< does not reference other samples */ + MP4_SDT_EARLIER_DISPLAY_TIMES_ALLOWED = 0x40, /**< subequent samples in GOP may display earlier */ + _MP4_SDT_RESERVED = 0x80 /**< reserved */ +} MP4SampleDependencyType; + +/** Read a track sample. + * + * MP4ReadSample reads the specified sample from the specified track. + * Typically this sample is then decoded in a codec dependent fashion and + * rendered in an appropriate fashion. + * + * The argument ppBytes allows for two possible approaches for + * buffering: + * + * If the calling application wishes to handle its own buffering it can set + * *ppBytes to the buffer it wishes to use. The calling application is + * responsible for ensuring that the buffer is large enough to hold the + * sample. This can be done by using either MP4GetSampleSize() or + * MP4GetTrackMaxSampleSize() to determine before-hand how large the + * receiving buffer must be. + * + * If the value of *ppBytes is NULL, then an appropriately sized buffer is + * automatically malloc'ed for the sample data and *ppBytes set to this + * pointer. The calling application is responsible for free'ing this + * memory. + * + * The last four arguments are pointers to variables that can receive + * optional sample information. + * + * Typically for audio none of these are needed. MPEG audio such as MP3 or + * AAC has a fixed sample duration and every sample can be accessed at + * random. + * + * For video, all of these optional values could be needed. MPEG video can + * be encoded at a variable frame rate, with only occasional random access + * points, and with "B frames" which cause the rendering (display) order + * of the video frames to differ from the storage/decoding order. + * + * Other media types fall between these two extremes. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param sampleId specifies which sample is to be read. + * Caveat: the first sample has id 1 not 0. + * @param ppBytes pointer to the pointer to the sample data. + * @param pNumBytes pointer to variable that will be hold the size in bytes + * of the sample. + * @param pStartTime if non-NULL, pointer to variable that will receive the + * starting timestamp for this sample. Caveat: The timestamp is in + * trackId's timescale. + * @param pDuration if non-NULL, pointer to variable that will receive the + * duration for this sample. Caveat: The duration is in + * trackId's timescale. + * @param pRenderingOffset if non-NULL, pointer to variable that will + * receive the rendering offset for this sample. Currently the only + * media type that needs this feature is MPEG video. Caveat: The offset + * is in trackId's timescale. + * @param pIsSyncSample if non-NULL, pointer to variable that will receive + * the state of the sync/random access flag for this sample. + * + * @return true on success, false on failure. + * + * @see MP4GetSampleSize(). + * @see MP4GetTrackMaxSampleSize(). + */ +MP4V2_EXPORT +bool MP4ReadSample( + /* input parameters */ + MP4FileHandle hFile, + MP4TrackId trackId, + MP4SampleId sampleId, + /* input/output parameters */ + uint8_t** ppBytes, + uint32_t* pNumBytes, + /* output parameters */ + MP4Timestamp* pStartTime DEFAULT(NULL), + MP4Duration* pDuration DEFAULT(NULL), + MP4Duration* pRenderingOffset DEFAULT(NULL), + bool* pIsSyncSample DEFAULT(NULL) ); + +/** Read a track sample based on a specified time. + * + * MP4ReadSampleFromTime is similar to MP4ReadSample() except the sample + * is specified by using a timestamp instead of sampleId. + * Typically this sample is then decoded in a codec dependent fashion and + * rendered in an appropriate fashion. + * + * The argument ppBytes allows for two possible approaches for + * buffering: + * + * If the calling application wishes to handle its own buffering it can set + * *ppBytes to the buffer it wishes to use. The calling application is + * responsible for ensuring that the buffer is large enough to hold the + * sample. This can be done by using either MP4GetSampleSize() or + * MP4GetTrackMaxSampleSize() to determine before-hand how large the + * receiving buffer must be. + * + * If the value of *ppBytes is NULL, then an appropriately sized buffer is + * automatically malloc'ed for the sample data and *ppBytes set to this + * pointer. The calling application is responsible for free'ing this + * memory. + * + * The last four arguments are pointers to variables that can receive + * optional sample information. + * + * Typically for audio none of these are needed. MPEG audio such as MP3 or + * AAC has a fixed sample duration and every sample can be accessed at + * random. + * + * For video, all of these optional values could be needed. MPEG video can + * be encoded at a variable frame rate, with only occasional random access + * points, and with "B frames" which cause the rendering (display) order + * of the video frames to differ from the storage/decoding order. + * + * Other media types fall between these two extremes. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param when specifies which sample is to be read based on a time in the + * track timeline. See MP4GetSampleIdFromTime() for details. + * @param ppBytes pointer to the pointer to the sample data. + * @param pNumBytes pointer to variable that will be hold the size in bytes + * of the sample. + * @param pStartTime if non-NULL, pointer to variable that will receive the + * starting timestamp for this sample. Caveat: The timestamp is in + * trackId's timescale. + * @param pDuration if non-NULL, pointer to variable that will receive the + * duration for this sample. Caveat: The duration is in + * trackId's timescale. + * @param pRenderingOffset if non-NULL, pointer to variable that will + * receive the rendering offset for this sample. Currently the only + * media type that needs this feature is MPEG video. Caveat: The offset + * is in trackId's timescale. + * @param pIsSyncSample if non-NULL, pointer to variable that will receive + * the state of the sync/random access flag for this sample. + * + * @return true on success, false on failure. + * + * @see MP4ReadSample(). + * @see MP4GetSampleIdFromTime(). + * @see MP4GetSampleSize(). + * @see MP4GetTrackMaxSampleSize(). + */ +MP4V2_EXPORT +bool MP4ReadSampleFromTime( + /* input parameters */ + MP4FileHandle hFile, + MP4TrackId trackId, + MP4Timestamp when, + /* input/output parameters */ + uint8_t** ppBytes, + uint32_t* pNumBytes, + /* output parameters */ + MP4Timestamp* pStartTime DEFAULT(NULL), + MP4Duration* pDuration DEFAULT(NULL), + MP4Duration* pRenderingOffset DEFAULT(NULL), + bool* pIsSyncSample DEFAULT(NULL) ); + +/** Write a track sample. + * + * MP4WriteSample writes the given sample at the end of the specified track. + * Currently the library does not support random insertion of samples into + * the track timeline. Note that with mp4 there cannot be any holes or + * overlapping samples in the track timeline. The last three arguments give + * optional sample information. + * + * The value of duration can be given as #MP4_INVALID_DURATION if all samples + * in the track have the same duration. This can be specified with + * MP4AddTrack() and related functions. + * + * Typically for audio none of the optional arguments are needed. MPEG audio + * such as MP3 or AAC has a fixed sample duration and every sample can be + * accessed at random. + * + * For video, all of the optional arguments could be needed. MPEG video + * can be encoded at a variable frame rate, with only occasional random + * access points, and with "B frames" which cause the rendering (display) + * order of the video frames to differ from the storage/decoding order. + * + * Other media types fall between these two extremes. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param pBytes pointer to sample data. + * @param numBytes length of sample data in bytes. + * @param duration sample duration. Caveat: should be in track timescale. + * @param renderingOffset the rendering offset for this sample. + * Currently the only media type that needs this feature is MPEG + * video. Caveat: The offset should be in the track timescale. + * @param isSyncSample the sync/random access flag for this sample. + * + * @return true on success, false on failure. + * + * @see MP4AddTrack(). + */ +MP4V2_EXPORT +bool MP4WriteSample( + MP4FileHandle hFile, + MP4TrackId trackId, + const uint8_t* pBytes, + uint32_t numBytes, + MP4Duration duration DEFAULT(MP4_INVALID_DURATION), + MP4Duration renderingOffset DEFAULT(0), + bool isSyncSample DEFAULT(true) ); + +/** Write a track sample and supply dependency information. + * + * MP4WriteSampleDependency writes the given sample at the end of the specified track. + * Currently the library does not support random insertion of samples into + * the track timeline. Note that with mp4 there cannot be any holes or + * overlapping samples in the track timeline. The last three arguments give + * optional sample information. + * + * The value of duration can be given as #MP4_INVALID_DURATION if all samples + * in the track have the same duration. This can be specified with + * MP4AddTrack() and related functions. + * + * When this method is used instead of MP4WriteSample() it enables sdtp + * atom to be written out. This atom may be used by advanced players to + * optimize trick-operations such as fast-fwd, reverse or scrubbing. + * + * An sdtp atom will always be written out if this method is used. + * To avoid writing the atom, use MP4WriteSample() instead. + * + * Intermixing use of MP4WriteSampleDependency() and MP4WriteSample() on the + * same track is not permitted. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param pBytes pointer to sample data. + * @param numBytes length of sample data in bytes. + * @param duration sample duration. Caveat: should be in track timescale. + * @param renderingOffset the rendering offset for this sample. + * Currently the only media type that needs this feature is MPEG + * video. Caveat: The offset should be in the track timescale. + * @param isSyncSample the sync/random access flag for this sample. + * @param dependencyFlags bitmask specifying sample dependency characteristics. + * See #MP4SampleDependencyType for bit constants. + * + * @return true on success, false on failure. + * + * @see MP4AddTrack(). + */ +MP4V2_EXPORT +bool MP4WriteSampleDependency( + MP4FileHandle hFile, + MP4TrackId trackId, + const uint8_t* pBytes, + uint32_t numBytes, + MP4Duration duration, + MP4Duration renderingOffset, + bool isSyncSample, + uint32_t dependencyFlags ); + +/** Make a copy of a sample. + * + * MP4CopySample creates a new sample based on an existing sample. Note that + * another copy of the media sample data is created in the file using this + * function. ie. this call is equivalent to MP4ReadSample() followed by + * MP4WriteSample(). + * + * Note that is the responsibility of the caller to ensure that the copied + * media sample makes sense in the destination track. eg. copying a video + * sample to an audio track is unlikely to result in anything good happening, + * even copying a sample from video track to another requires that the tracks + * use the same encoding and that issues such as image size are addressed. + * + * @param srcFile source sample file handle. + * @param srcTrackId source sample track id. + * @param srcSampleId source sample id. + * @param dstFile destination file handle for new (copied) sample. + * If the value is #MP4_INVALID_FILE_HANDLE, the copy is created in + * the same file as srcFile. + * @param dstTrackId destination track id for new sample. + * If the value is #MP4_INVALID_TRACK_ID, the the copy is created in + * the same track as the srcTrackId. + * @param dstSampleDuration duration in track timescale for new sample. + * If the value is #MP4_INVALID_DURATION, then the duration of + * the source sample is used. + * + * @return On success, thew id of the new sample. + * On error, #MP4_INVALID_SAMPLE_ID. + * + * @see MP4ReadSample(). + * @see MP4WriteSample(). + */ +MP4V2_EXPORT +bool MP4CopySample( + MP4FileHandle srcFile, + MP4TrackId srcTrackId, + MP4SampleId srcSampleId, + MP4FileHandle dstFile DEFAULT(MP4_INVALID_FILE_HANDLE), + MP4TrackId dstTrackId DEFAULT(MP4_INVALID_TRACK_ID), + MP4Duration dstSampleDuration DEFAULT(MP4_INVALID_DURATION) ); + +/** Make a copy of a sample. + * + * MP4EncAndCopySample is similar to MP4CopySample() except that it + * offers an encryption hook to the caller. + * + * @param srcFile source sample file handle. + * @param srcTrackId source sample track id. + * @param srcSampleId source sample id. + * @param encfcnp undocumented. + * @param encfcnparam1 undocumented. + * @param dstFile destination file handle for new (copied) sample. + * If the value is #MP4_INVALID_FILE_HANDLE, the copy is created in + * the same file as srcFile. + * @param dstTrackId destination track id for new sample. + * If the value is #MP4_INVALID_TRACK_ID, the the copy is created in + * the same track as the srcTrackId. + * @param dstSampleDuration duration in track timescale for new sample. + * If the value is #MP4_INVALID_DURATION, then the duration of + * the source sample is used. + * + * @return On success, thew id of the new sample. + * On error, #MP4_INVALID_SAMPLE_ID. + * + * @see MP4CopySample(). + */ +MP4V2_EXPORT +bool MP4EncAndCopySample( + MP4FileHandle srcFile, + MP4TrackId srcTrackId, + MP4SampleId srcSampleId, + encryptFunc_t encfcnp, + uint32_t encfcnparam1, + MP4FileHandle dstFile DEFAULT(MP4_INVALID_FILE_HANDLE), + MP4TrackId dstTrackId DEFAULT(MP4_INVALID_TRACK_ID), + MP4Duration dstSampleDuration DEFAULT(MP4_INVALID_DURATION) ); + +/** Not implemented. + */ +MP4V2_EXPORT +bool MP4ReferenceSample( + MP4FileHandle srcFile, + MP4TrackId srcTrackId, + MP4SampleId srcSampleId, + MP4FileHandle dstFile, + MP4TrackId dstTrackId, + MP4Duration dstSampleDuration DEFAULT(MP4_INVALID_DURATION) ); + +/** Get size of a track sample. + * + * MP4GetSampleSize returns the size in bytes of the specified sample from the + * the specified track. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param sampleId id of sample for operation. Caveat: the first sample has + * id 1, not 0. + * + * @return On success the sample size in bytes. On error, 0. + */ +MP4V2_EXPORT +uint32_t MP4GetSampleSize( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4SampleId sampleId); + +/** Get the maximum sample size of a track. + * + * MP4GetTrackMaxSampleSize returns the maximum size in bytes of all the + * samples in the specified track. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * + * @return On success, the maximum sample size in bytes. On error, 0. + * + * @see MP4GetSampleSize(). + */ +MP4V2_EXPORT +uint32_t MP4GetTrackMaxSampleSize( + MP4FileHandle hFile, + MP4TrackId trackId ); + +/** Get sample id of a specified time. + * + * MP4GetSampleIdFromTime returns the sample id of the track sample in which + * the specified time occurs. + * + * The specified time should be in the track timescale. + * + * It is wise to use MP4GetSampleTime() with the returned sample id so one + * can adjust for any difference between the specified time and the actual + * start time of the sample. + * + * If the calling application needs a sample that can be accessed randomly + * then the wantSyncSample argument should be set to true. This could + * be the case for a player that is implementing a positioning function and + * needs to be able to start decoding a track from the returned sample id. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param when time in track timescale. + * @param wantSyncSample specifies if the result sample id must correspond + * to a sample whose sync/random access flag is true. + * + * @return On success, the sample id that occurs at the specified time. + * On error, #MP4_INVALID_SAMPLE_ID. + * + * @see MP4ConvertToTrackTimestamp() for how to map a time value to this + * timescale. + */ +MP4V2_EXPORT +MP4SampleId MP4GetSampleIdFromTime( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4Timestamp when, + bool wantSyncSample DEFAULT(false) ); + +/** Get start time of track sample. + * + * MP4GetSampleTime returns the start time of the specified sample from + * the specified track in the track timescale units. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param sampleId id of sample for operation. Caveat: the first sample has + * id 1, not 0. + * + * @return On success, sample start time in track timescale units. + * On error, #MP4_INVALID_TIMESTAMP. + * + * @see MP4ConvertFromTrackTimestamp() for how to map this value to another + * timescale. + */ +MP4V2_EXPORT +MP4Timestamp MP4GetSampleTime( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4SampleId sampleId ); + +/** Get the duration of a track sample. + * + * MP4GetSampleDuration returns the duration of the specified sample from + * the specified track in the track timescale units. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param sampleId id of sample for operation. Caveat: the first sample has + * id 1, not 0. + * + * @return On success, the sample duration in track timescale units. + * On error, #MP4_INVALID_DURATION. + * + * @see MP4ConvertFromTrackDuration() for how to map this value to another + * timescale. + */ +MP4V2_EXPORT +MP4Duration MP4GetSampleDuration( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4SampleId sampleId ); + +/** Get the rendering offset of a track sample. + * + * MP4GetSampleRenderingOffset returns the rendering offset of the specified + * sample from the specified track in the track timescale units. + * + * The sample rendering offset is typically zero for all media types other + * than video. For video, encodings such as those defined by MPEG have + * three types of frames: I, P, and B. To increase coding efficiency B + * frames can depend on I or P frames that should be rendered after the B + * frame. However to decode the B frame the I or P frame must already have + * been decoded. This situation is addressed by placing the frames in + * decoding order in the video track, and then setting the rendering offset + * property to indicate when the video frame should actually be rendered to + * the screen. Hence the start time of a sample indicates when it should be + * decoded, the start time plus the rendering offset indicates when it + * should be rendered. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param sampleId id of sample for operation. Caveat: the first sample has + * id 1, not 0. + * + * @return On success, the rendering offset in track timescale units. + * On error, #MP4_INVALID_DURATION. + * + * @see MP4ConvertFromTrackDuration() for how to map this value to another + * timescale. + */ +MP4V2_EXPORT +MP4Duration MP4GetSampleRenderingOffset( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4SampleId sampleId ); + +/** Set the rendering offset of a track sample. + * + * MP4SetSampleRenderingOffset sets the rendering offset of the specified + * sample from the specified track in the track timescale units. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param sampleId id of sample for operation. Caveat: the first sample has + * id 1, not 0. + * @param renderingOffset new offset value in timescale units. + * + * @return true on success, false on failure. + * + * @see MP4ConvertToTrackDuration() for how to map this value from another + * timescale. + * @see MP4GetSampleRenderingOffset() for a description of this sample + * property. + */ +MP4V2_EXPORT +bool MP4SetSampleRenderingOffset( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4SampleId sampleId, + MP4Duration renderingOffset ); + +/** Get sync/random access state of sample. + * + * MP4GetSampleSync returns the state of the sync/random access flag of + * the specified sample from the specified track. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param sampleId id of sample for operation. Caveat: the first sample has + * id 1, not 0. + * + * @return 1 when true, 0 when false. On error, -1. + */ +MP4V2_EXPORT +int8_t MP4GetSampleSync( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4SampleId sampleId ); + +/* @} ***********************************************************************/ + +#endif /* MP4V2_SAMPLE_H */ diff --git a/mp4v2/mp4v2/streaming.h b/mp4v2/mp4v2/streaming.h new file mode 100644 index 0000000..36389d6 --- /dev/null +++ b/mp4v2/mp4v2/streaming.h @@ -0,0 +1,163 @@ +#ifndef MP4V2_STREAMING_H +#define MP4V2_STREAMING_H + +/**************************************************************************//** + * + * @defgroup mp4_hint MP4v2 Streaming + * @{ + * + *****************************************************************************/ + +MP4V2_EXPORT +bool MP4GetHintTrackRtpPayload( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + char** ppPayloadName DEFAULT(NULL), + uint8_t* pPayloadNumber DEFAULT(NULL), + uint16_t* pMaxPayloadSize DEFAULT(NULL), + char** ppEncodingParams DEFAULT(NULL) ); + +#define MP4_SET_DYNAMIC_PAYLOAD 0xff + +MP4V2_EXPORT +bool MP4SetHintTrackRtpPayload( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + const char* pPayloadName, + uint8_t* pPayloadNumber, + uint16_t maxPayloadSize DEFAULT(0), + const char * encode_params DEFAULT(NULL), + bool include_rtp_map DEFAULT(true), + bool include_mpeg4_esid DEFAULT(true) ); + +MP4V2_EXPORT +const char* MP4GetSessionSdp( + MP4FileHandle hFile ); + +MP4V2_EXPORT +bool MP4SetSessionSdp( + MP4FileHandle hFile, + const char* sdpString ); + +MP4V2_EXPORT +bool MP4AppendSessionSdp( + MP4FileHandle hFile, + const char* sdpString ); + +MP4V2_EXPORT +const char* MP4GetHintTrackSdp( + MP4FileHandle hFile, + MP4TrackId hintTrackId ); + +MP4V2_EXPORT +bool MP4SetHintTrackSdp( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + const char* sdpString ); + +MP4V2_EXPORT +bool MP4AppendHintTrackSdp( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + const char* sdpString ); + +MP4V2_EXPORT +MP4TrackId MP4GetHintTrackReferenceTrackId( + MP4FileHandle hFile, + MP4TrackId hintTrackId ); + +MP4V2_EXPORT +bool MP4ReadRtpHint( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + MP4SampleId hintSampleId, + uint16_t* pNumPackets DEFAULT(NULL) ); + +MP4V2_EXPORT +uint16_t MP4GetRtpHintNumberOfPackets( + MP4FileHandle hFile, + MP4TrackId hintTrackId ); + +MP4V2_EXPORT +int8_t MP4GetRtpPacketBFrame( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + uint16_t packetIndex ); + +MP4V2_EXPORT +int32_t MP4GetRtpPacketTransmitOffset( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + uint16_t packetIndex ); + +MP4V2_EXPORT +bool MP4ReadRtpPacket( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + uint16_t packetIndex, + uint8_t** ppBytes, + uint32_t* pNumBytes, + uint32_t ssrc DEFAULT(0), + bool includeHeader DEFAULT(true), + bool includePayload DEFAULT(true) ); + +MP4V2_EXPORT +MP4Timestamp MP4GetRtpTimestampStart( + MP4FileHandle hFile, + MP4TrackId hintTrackId ); + +MP4V2_EXPORT +bool MP4SetRtpTimestampStart( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + MP4Timestamp rtpStart ); + +MP4V2_EXPORT +bool MP4AddRtpHint( + MP4FileHandle hFile, + MP4TrackId hintTrackId ); + +MP4V2_EXPORT +bool MP4AddRtpVideoHint( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + bool isBframe DEFAULT(false), + uint32_t timestampOffset DEFAULT(0) ); + +MP4V2_EXPORT +bool MP4AddRtpPacket( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + bool setMbit DEFAULT(false), + int32_t transmitOffset DEFAULT(0) ); + +MP4V2_EXPORT +bool MP4AddRtpImmediateData( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + const uint8_t* pBytes, + uint32_t numBytes ); + +MP4V2_EXPORT +bool MP4AddRtpSampleData( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + MP4SampleId sampleId, + uint32_t dataOffset, + uint32_t dataLength ); + +MP4V2_EXPORT +bool MP4AddRtpESConfigurationPacket( + MP4FileHandle hFile, + MP4TrackId hintTrackId ); + +MP4V2_EXPORT +bool MP4WriteRtpHint( + MP4FileHandle hFile, + MP4TrackId hintTrackId, + MP4Duration duration, + bool isSyncSample DEFAULT(true) ); + +/** @} ***********************************************************************/ + +#endif /* MP4V2_STREAMING_H */ diff --git a/mp4v2/mp4v2/track.h b/mp4v2/mp4v2/track.h new file mode 100644 index 0000000..d22890f --- /dev/null +++ b/mp4v2/mp4v2/track.h @@ -0,0 +1,506 @@ +#ifndef MP4V2_TRACK_H +#define MP4V2_TRACK_H + +/**************************************************************************//** + * + * @defgroup mp4_track MP4v2 Track + * @{ + * + *****************************************************************************/ + +/** Add a user defined track. + * + * MP4AddTrack adds a user defined track to the mp4 file. Care should be + * taken to avoid any of the standardized track type names. A useful + * convention is use only uppercase characters for user defined track types. + * The string should be exactly four characters in length, e.g. "MINE". + * + * Note this should not be used to add any of the known track types defined + * in the MP4 standard (ISO/IEC 14496-1:2001). + * + * @param hFile handle of file for operation. + * @param type specifies the type of track to be added. + * @param timeScale the time scale in ticks per second of the track. Default is 1000. + * + * @return On success, the track-id of new track. + * On failure, #MP4_INVALID_TRACK_ID. + */ +MP4V2_EXPORT +MP4TrackId MP4AddTrack( + MP4FileHandle hFile, + const char* type, + uint32_t timeScale DEFAULT(MP4_MSECS_TIME_SCALE) ); + +/** Add an MPEG-4 systems track. + * + * MP4AddSystemsTrack adds an MPEG-4 Systems track to the mp4 file. Note + * this should not be used to add OD or scene tracks, MP4AddODTrack() and + * MP4AddSceneTrack() should be used for those purposes. Other known + * MPEG-4 System track types are: + * @li #MP4_CLOCK_TRACK_TYPE + * @li #MP4_MPEG7_TRACK_TYPE + * @li #MP4_OCI_TRACK_TYPE + * @li #MP4_IPMP_TRACK_TYPE + * @li #MP4_MPEGJ_TRACK_TYPE + * + * @param hFile handle of file for operation. + * @param type specifies the type of track to be added. + * + * @return On success, the track-id of new track. + * On failure, #MP4_INVALID_TRACK_ID. + */ +MP4V2_EXPORT +MP4TrackId MP4AddSystemsTrack( + MP4FileHandle hFile, + const char* type ); + +/** Add a object descriptor (OD) track. + * + * MP4AddODTrack adds an object descriptor (aka OD) track to the mp4 file. + * MP4WriteSample() can then be used to add the desired OD commands to the + * track. The burden is currently on the calling application to understand + * OD. + * + * Those wishing to have a simple audio/video scene without understanding + * OD may wish to use MP4MakeIsmaCompliant() to create the minimal OD and + * BIFS information. + * + * @param hFile handle of file for operation. + * + * @return On success, the track-id of new track. + * On failure, #MP4_INVALID_TRACK_ID. + */ +MP4V2_EXPORT +MP4TrackId MP4AddODTrack( + MP4FileHandle hFile ); + +/** Add a scene (BIFS) track. + * + * MP4AddSceneTrack adds a scene (aka BIFS) track to the mp4 file. + * MP4WriteSample() can then be used to add the desired BIFS commands to + * the track. The burden is currently on the calling application to + * understand BIFS. + * + * Those wishing to have a simple audio/video scene without understanding + * BIFS may wish to use MP4MakeIsmaCompliant() to create the minimal OD + * and BIFS information. + * + * @param hFile handle of file for operation. + * + * @return On success, the track-id of new track. + * On failure, #MP4_INVALID_TRACK_ID. + */ +MP4V2_EXPORT +MP4TrackId MP4AddSceneTrack( + MP4FileHandle hFile ); + +/** Add audio track to mp4 file. + * + * MP4AddAudioTrack adds an audio track to the mp4 file. MP4WriteSample() + * can then be used to add the desired audio samples. + * + * It is recommended that the time scale be set to the sampling frequency + * (eg. 44100 Hz) of the audio so as to preserve the timing information + * accurately. + * + * If the audio encoding uses a fixed duration for each sample that should + * be specified here. If not then the value #MP4_INVALID_DURATION + * should be given for the sampleDuration argument. + * + * @param hFile handle of file for operation. + * @param timeScale the time scale in ticks per second of the track. + * @param sampleDuration the fixed duration for all track samples. + * Caveat: the value should be in track-timescale units. + * @param audioType the audio encoding type. + * See MP4GetTrackEsdsObjectTypeId() for known values. + * + * @return On success, the track-id of the new track. + * On error, #MP4_INVALID_TRACK_ID. + */ +MP4V2_EXPORT +MP4TrackId MP4AddAudioTrack( + MP4FileHandle hFile, + uint32_t timeScale, + MP4Duration sampleDuration, + uint8_t audioType DEFAULT(MP4_MPEG4_AUDIO_TYPE) ); + +/** Add ulaw track to mp4 file. + * + * MP4AddULawAudioTrack adds a ulaw track to the mp4 file. MP4WriteSample() + * can then be used to add the desired audio samples. + * + * @param hFile handle of file for operation. + * @param timeScale the time scale in ticks per second of the track. + * + * @return On success, the track-id of the new track. + * On error, #MP4_INVALID_TRACK_ID. +*/ +MP4V2_EXPORT +MP4TrackId MP4AddULawAudioTrack( + MP4FileHandle hFile, + uint32_t timeScale); + +/** Add alaw track to mp4 file. + * + * MP4AddALawAudioTrack adds a alaw track to the mp4 file. MP4WriteSample() + * can then be used to add the desired audio samples. + * + * @param hFile handle of file for operation. + * @param timeScale the time scale in ticks per second of the track. + * + * @return On success, the track-id of the new track. + * On error, #MP4_INVALID_TRACK_ID. +*/ +MP4V2_EXPORT +MP4TrackId MP4AddALawAudioTrack( + MP4FileHandle hFile, + uint32_t timeScale); + +MP4V2_EXPORT +MP4TrackId MP4AddAC3AudioTrack( + MP4FileHandle hFile, + uint32_t samplingRate, + uint8_t fscod, + uint8_t bsid, + uint8_t bsmod, + uint8_t acmod, + uint8_t lfeon, + uint8_t bit_rate_code ); + +MP4V2_EXPORT +MP4TrackId MP4AddALACAudioTrack( + MP4FileHandle hFile, + uint32_t samplingRate ); + +MP4V2_EXPORT +MP4TrackId MP4AddAmrAudioTrack( + MP4FileHandle hFile, + uint32_t timeScale, + uint16_t modeSet, + uint8_t modeChangePeriod, + uint8_t framesPerSample, + bool isAmrWB ); + +MP4V2_EXPORT +void MP4SetAmrVendor( + MP4FileHandle hFile, + MP4TrackId trackId, + uint32_t vendor ); + +MP4V2_EXPORT +void MP4SetAmrDecoderVersion( + MP4FileHandle hFile, + MP4TrackId trackId, + uint8_t decoderVersion ); + +MP4V2_EXPORT +void MP4SetAmrModeSet( + MP4FileHandle hFile, + MP4TrackId trakId, + uint16_t modeSet ); + +MP4V2_EXPORT +uint16_t MP4GetAmrModeSet( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +MP4TrackId MP4AddHrefTrack( + MP4FileHandle hFile, + uint32_t timeScale, + MP4Duration sampleDuration, + const char* base_url DEFAULT(NULL) ); + +MP4V2_EXPORT +const char* MP4GetHrefTrackBaseUrl( + MP4FileHandle hFile, + MP4TrackId trackId ); + +/** Add a video track. + * + * MP4AddVideoTrack adds a video track to the mp4 file. MP4WriteSample() + * can then be used to add the desired video samples. + * + * It is recommended that the time scale be set to 90000 so as to preserve + * the timing information accurately for the range of video frame rates + * commonly in use. + * + * If the video frame rate is to be fixed then the sampleDuration argument + * should be give the appropriate fixed value. If the video frame rate is + * to be variable then the value #MP4_INVALID_DURATION should be + * given for the sampleDuration argument. + * + * @param hFile handle of file for operation. + * @param timeScale the timescale in ticks per second of the track. + * @param sampleDuration specifies fixed sample duration for all track + * samples. Caveat: the value should be in track timescale units. + * @param width specifies the video frame width in pixels. + * @param height specifies the video frame height in pixels. + * @param videoType specifies the video encoding type. + * See MP4GetTrackVideoType() for known values. + * + * @return On success, the track-id of the new track. + * On error, #MP4_INVALID_TRACK_ID. + */ +MP4V2_EXPORT +MP4TrackId MP4AddVideoTrack( + MP4FileHandle hFile, + uint32_t timeScale, + MP4Duration sampleDuration, + uint16_t width, + uint16_t height, + uint8_t videoType DEFAULT(MP4_MPEG4_VIDEO_TYPE) ); + +MP4V2_EXPORT +MP4TrackId MP4AddJpegVideoTrack( + MP4FileHandle hFile, + uint32_t timeScale, + MP4Duration sampleDuration, + uint16_t width, + uint16_t height); + +MP4V2_EXPORT +MP4TrackId MP4AddH264VideoTrack( + MP4FileHandle hFile, + uint32_t timeScale, + MP4Duration sampleDuration, + uint16_t width, + uint16_t height, + uint8_t AVCProfileIndication, + uint8_t profile_compat, + uint8_t AVCLevelIndication, + uint8_t sampleLenFieldSizeMinusOne ); + +MP4V2_EXPORT +void MP4AddH264SequenceParameterSet( + MP4FileHandle hFile, + MP4TrackId trackId, + const uint8_t* pSequence, + uint16_t sequenceLen ); + +MP4V2_EXPORT +void MP4AddH264PictureParameterSet( + MP4FileHandle hFile, + MP4TrackId trackId, + const uint8_t* pPict, + uint16_t pictLen ); + +MP4V2_EXPORT +void MP4SetH263Vendor( + MP4FileHandle hFile, + MP4TrackId trackId, + uint32_t vendor ); + +MP4V2_EXPORT +void MP4SetH263DecoderVersion( + MP4FileHandle hFile, + MP4TrackId trackId, + uint8_t decoderVersion ); + +MP4V2_EXPORT +void MP4SetH263Bitrates( + MP4FileHandle hFile, + MP4TrackId trackId, + uint32_t avgBitrate, + uint32_t maxBitrate ); + +MP4V2_EXPORT +MP4TrackId MP4AddH263VideoTrack( + MP4FileHandle hFile, + uint32_t timeScale, + MP4Duration sampleDuration, + uint16_t width, + uint16_t height, + uint8_t h263Level, + uint8_t h263Profile, + uint32_t avgBitrate, + uint32_t maxBitrate ); + +/** Add a hint track. + * + * MP4AddHintTrack adds a hint track to the mp4 file. A hint track is used + * to describe how to send the reference media track over a particular + * network transport. In the case of the IETF RTP protocol, the hint track + * describes how the media data should be placed into packets and any + * media specific protocol headers that should be added. + * + * Typically there is a one to one correspondence between reference media + * track samples and hint track samples. The start time, duration, and + * sync flags are typically the same, however provisions are made for + * deviations from this rule. + * + * The MP4 library provides extensive support for RTP hint tracks. This + * includes a easy to use API to create RTP hint tracks, and read out + * fully constructed RTP packets based on the hint track. + * + * @param hFile handle of file for operation. + * @param refTrackId specifies the reference media track for this hint track. + * + * @return On success, the track-id of the new track. + * On error, #MP4_INVALID_TRACK_ID. + */ +MP4V2_EXPORT +MP4TrackId MP4AddHintTrack( + MP4FileHandle hFile, + MP4TrackId refTrackId ); + +MP4V2_EXPORT +MP4TrackId MP4AddTextTrack( + MP4FileHandle hFile, + MP4TrackId refTrackId ); + +MP4V2_EXPORT +MP4TrackId MP4AddSubtitleTrack( + MP4FileHandle hFile, + uint32_t timescale, + uint16_t width, + uint16_t height ); + +/** Add a closed caption track. + * + * MP4AddCCTrack adds a closed caption track track to the mp4 file. MP4WriteSample() + * can then be used to add the desired video samples. + * + * @param hFile handle of file for operation. + * @param timeScale the timescale in ticks per second of the track. + * @param width specifies the video frame width in pixels. + * @param height specifies the video frame height in pixels. + * + * @return On success, the track-id of the new track. + * On error, #MP4_INVALID_TRACK_ID. + */ +MP4V2_EXPORT +MP4TrackId MP4AddCCTrack( + MP4FileHandle hFile, + uint32_t timeScale, + uint16_t width, + uint16_t height ); + +MP4V2_EXPORT +MP4TrackId MP4AddSubpicTrack( + MP4FileHandle hFile, + uint32_t timescale, + uint16_t width, + uint16_t height ); + +MP4V2_EXPORT +MP4TrackId MP4AddPixelAspectRatio( + MP4FileHandle hFile, + MP4TrackId refTrackId, + uint32_t hSpacing, + uint32_t vSpacing ); + +MP4V2_EXPORT +MP4TrackId MP4AddCleanAperture( + MP4FileHandle hFile, + MP4TrackId trackId, + uint32_t cleanApertureWidthN, uint32_t cleanApertureWidthD, + uint32_t cleanApertureHeightN, uint32_t cleanApertureHeightD, + uint32_t horizOffN, uint32_t horizOffD, + uint32_t vertOffN, uint32_t vertOffD ); + +MP4V2_EXPORT +MP4TrackId MP4AddColr( + MP4FileHandle hFile, + MP4TrackId refTrackId, + uint16_t primary, + uint16_t transfer, + uint16_t matrix ); + +MP4V2_EXPORT +MP4TrackId MP4CloneTrack( + MP4FileHandle srcFile, + MP4TrackId srcTrackId, + MP4FileHandle dstFile DEFAULT(MP4_INVALID_FILE_HANDLE), + MP4TrackId dstHintTrackReferenceTrack DEFAULT(MP4_INVALID_TRACK_ID) ); + +MP4V2_EXPORT +MP4TrackId MP4CopyTrack( + MP4FileHandle srcFile, + MP4TrackId srcTrackId, + MP4FileHandle dstFile DEFAULT(MP4_INVALID_FILE_HANDLE), + bool applyEdits DEFAULT(false), + MP4TrackId dstHintTrackReferenceTrack DEFAULT(MP4_INVALID_TRACK_ID) ); + +MP4V2_EXPORT +bool MP4DeleteTrack( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +uint32_t MP4GetNumberOfTracks( + MP4FileHandle hFile, + const char* type DEFAULT(NULL), + uint8_t subType DEFAULT(0) ); + +MP4V2_EXPORT +MP4TrackId MP4FindTrackId( + MP4FileHandle hFile, + uint16_t index, + const char* type DEFAULT(NULL), + uint8_t subType DEFAULT(0) ); + +MP4V2_EXPORT +uint16_t MP4FindTrackIndex( + MP4FileHandle hFile, + MP4TrackId trackId ); + +/** Get maximum duration of chunk. + * + * MP4GetTrackDurationPerChunk gets the maximum duration for each chunk. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param duration out value of duration in track timescale units. + * + * return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4GetTrackDurationPerChunk( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4Duration* duration ); + +/** Set maximum duration of chunk. + * + * MP4SetTrackDurationPerChunk sets the maximum duration for each chunk. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param duration in timescale units. + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4SetTrackDurationPerChunk( + MP4FileHandle hFile, + MP4TrackId trackId, + MP4Duration duration ); + +/** + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4AddTrackReference( + MP4FileHandle hFile, + const char* trefName, + MP4TrackId trackId, + MP4TrackId refTrackId ); + +MP4V2_EXPORT +bool MP4RemoveAllTrackReferences( + MP4FileHandle hFile, + const char* trefName, + MP4TrackId trackId ); + +MP4V2_EXPORT +bool MP4AddIPodUUID( + MP4FileHandle hFile, + MP4TrackId trackId ); + +/** @} ***********************************************************************/ + +#endif /* MP4V2_TRACK_H */ diff --git a/mp4v2/mp4v2/track_prop.h b/mp4v2/mp4v2/track_prop.h new file mode 100644 index 0000000..37d7643 --- /dev/null +++ b/mp4v2/mp4v2/track_prop.h @@ -0,0 +1,337 @@ +#ifndef MP4V2_TRACK_PROP_H +#define MP4V2_TRACK_PROP_H + +/**************************************************************************//** + * + * @defgroup mp4_track_prop MP4v2 Track Property + * @{ + * + *****************************************************************************/ + +/* specific track properties */ + +MP4V2_EXPORT +bool MP4HaveTrackAtom( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* atomname ); + +/** Get the track type. + * + * MP4GetTrackType gets the type of the track with the specified track id. + * + * Note: the library does not provide a MP4SetTrackType function, the + * track type needs to be specified when the track is created, e.g. + * MP4AddSystemsTrack(MP4_OCI_TRACK_TYPE). + * + * Known track types are: + * @li #MP4_OD_TRACK_TYPE + * @li #MP4_SCENE_TRACK_TYPE + * @li #MP4_AUDIO_TRACK_TYPE + * @li #MP4_VIDEO_TRACK_TYPE + * @li #MP4_HINT_TRACK_TYPE + * @li #MP4_CNTL_TRACK_TYPE + * @li #MP4_TEXT_TRACK_TYPE + * @li #MP4_CLOCK_TRACK_TYPE + * @li #MP4_MPEG7_TRACK_TYPE + * @li #MP4_OCI_TRACK_TYPE + * @li #MP4_IPMP_TRACK_TYPE + * @li #MP4_MPEGJ_TRACK_TYPE + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * + * @return On success, a string indicating track type. On failure, NULL. + */ +MP4V2_EXPORT +const char* MP4GetTrackType( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +const char* MP4GetTrackMediaDataName( + MP4FileHandle hFile, + MP4TrackId trackId ); + +/* + * MP4GetTrackMediaDataOriginalFormat is to be used to get the original + * MediaDataName if a track has been encrypted. + */ + +MP4V2_EXPORT +bool MP4GetTrackMediaDataOriginalFormat( + MP4FileHandle hFile, + MP4TrackId trackId, + char* originalFormat, + uint32_t buflen ); + +MP4V2_EXPORT +MP4Duration MP4GetTrackDuration( + MP4FileHandle hFile, + MP4TrackId trackId ); + +/** Get the time scale of a track. + * + * MP4GetTrackTimeScale returns the time scale of the specified track in + * the mp4 file. The time scale determines the number of clock ticks per + * second for this track. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * + * @return timescale (ticks per second) of the track in the mp4 file. + */ +MP4V2_EXPORT +uint32_t MP4GetTrackTimeScale( + MP4FileHandle hFile, + MP4TrackId trackId ); + +/** Set the time scale of a track. + * + * MP4SetTrackTimeScale sets the time scale of the specified track in the + * mp4 file. The time scale determines the number of clock ticks per + * second for this track. + * + * Typically this value is set once when the track is created. However + * this call can be used to modify the value if that is desired. Since + * track sample durations are expressed in units of the track time scale, + * any change to the time scale value will effect the real time duration + * of the samples. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param timeScale desired time scale for the track. + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4SetTrackTimeScale( + MP4FileHandle hFile, + MP4TrackId trackId, + uint32_t value ); + +/** Get ISO-639-2/T language code of a track. + * The language code is a 3-char alpha code consisting of lower-case letters. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param code buffer to hold 3-char+null (4-bytes total). + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4GetTrackLanguage( + MP4FileHandle hFile, + MP4TrackId trackId, + char* code ); + +/** Set ISO-639-2/T language code of a track. + * The language code is a 3-char alpha code consisting of lower-case letters. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * @param code 3-char language code. + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4SetTrackLanguage( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* code ); + +/** Get track name. + * + * MP4GetTrackName gets the name of the track via udta.name property. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4GetTrackName( + MP4FileHandle hFile, + MP4TrackId trackId, + char** name ); + +/** Set track name. + * + * MP4SetTrackName sets the name of the track via udta.name property. + * The udta atom is created if needed. + * + * @param hFile handle of file for operation. + * @param trackId id of track for operation. + * + * @return true on success, false on failure. + */ +MP4V2_EXPORT +bool MP4SetTrackName( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* name ); + +MP4V2_EXPORT +uint8_t MP4GetTrackAudioMpeg4Type( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +uint8_t MP4GetTrackEsdsObjectTypeId( + MP4FileHandle hFile, + MP4TrackId trackId ); + +/* returns MP4_INVALID_DURATION if track samples do not have a fixed duration */ +MP4V2_EXPORT +MP4Duration MP4GetTrackFixedSampleDuration( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +uint32_t MP4GetTrackBitRate( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +bool MP4GetTrackVideoMetadata( + MP4FileHandle hFile, + MP4TrackId trackId, + uint8_t** ppConfig, + uint32_t* pConfigSize ); + +MP4V2_EXPORT +bool MP4GetTrackESConfiguration( + MP4FileHandle hFile, + MP4TrackId trackId, + uint8_t** ppConfig, + uint32_t* pConfigSize ); + +MP4V2_EXPORT +bool MP4SetTrackESConfiguration( + MP4FileHandle hFile, + MP4TrackId trackId, + const uint8_t* pConfig, + uint32_t configSize ); + +/* h264 information routines */ +MP4V2_EXPORT +bool MP4GetTrackH264ProfileLevel( + MP4FileHandle hFile, + MP4TrackId trackId, + uint8_t* pProfile, + uint8_t* pLevel ); + +MP4V2_EXPORT +bool MP4GetTrackH264SeqPictHeaders( + MP4FileHandle hFile, + MP4TrackId trackId, + uint8_t*** pSeqHeaders, + uint32_t** pSeqHeaderSize, + uint8_t*** pPictHeader, + uint32_t** pPictHeaderSize ); + +MP4V2_EXPORT +bool MP4GetTrackH264LengthSize( + MP4FileHandle hFile, + MP4TrackId trackId, + uint32_t* pLength ); + +MP4V2_EXPORT +MP4SampleId MP4GetTrackNumberOfSamples( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +uint16_t MP4GetTrackVideoWidth( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +uint16_t MP4GetTrackVideoHeight( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +double MP4GetTrackVideoFrameRate( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +int MP4GetTrackAudioChannels( + MP4FileHandle hFile, + MP4TrackId trackId ); + +MP4V2_EXPORT +bool MP4IsIsmaCrypMediaTrack( + MP4FileHandle hFile, + MP4TrackId trackId ); + +/* generic track properties */ + +MP4V2_EXPORT +bool MP4HaveTrackAtom( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* atomName ); + +MP4V2_EXPORT +bool MP4GetTrackIntegerProperty( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* propName, + uint64_t* retvalue ); + +MP4V2_EXPORT +bool MP4GetTrackFloatProperty( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* propName, + float* ret_value ); + +MP4V2_EXPORT +bool MP4GetTrackStringProperty( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* propName, + const char** retvalue ); + +MP4V2_EXPORT +bool MP4GetTrackBytesProperty( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* propName, + uint8_t** ppValue, + uint32_t* pValueSize ); + +MP4V2_EXPORT +bool MP4SetTrackIntegerProperty( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* propName, + int64_t value ); + +MP4V2_EXPORT +bool MP4SetTrackFloatProperty( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* propName, + float value ); + +MP4V2_EXPORT +bool MP4SetTrackStringProperty( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* propName, + const char* value ); + +MP4V2_EXPORT +bool MP4SetTrackBytesProperty( + MP4FileHandle hFile, + MP4TrackId trackId, + const char* propName, + const uint8_t* pValue, + uint32_t valueSize); + +/** @} ***********************************************************************/ + +#endif /* MP4V2_TRACK_PROP_H */