First import.
This commit is contained in:
1 parent
4e61250dc6
commit
796e9691ce
114 files changed
+37004
-44
No files matched your search
Executable
+251
@@ -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 <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <limits.h>
|
||||
#include <TargetConditionals.h>
|
||||
#include <AvailabilityMacros.h>
|
||||
|
||||
#ifdef __OBJC__
|
||||
#import <Foundation/NSArray.h>
|
||||
#import <Foundation/NSData.h>
|
||||
#import <Foundation/NSDictionary.h>
|
||||
#import <Foundation/NSError.h>
|
||||
#import <Foundation/NSObjCRuntime.h>
|
||||
#import <Foundation/NSString.h>
|
||||
#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
|
||||
Executable
+3065
File diff suppressed because it is too large.
Load diff
-13
@@ -1,13 +0,0 @@
|
||||
//
|
||||
// MP42.h
|
||||
// MP42
|
||||
//
|
||||
// Created by Damiano Galassi on 01/11/13.
|
||||
// Copyright (c) 2013 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface MP42 : NSObject
|
||||
|
||||
@end
|
||||
-13
@@ -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
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// MP42AACFileImporter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 07/12/10.
|
||||
// Copyright 2010 Damiano Galassi All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42FileImporter.h"
|
||||
|
||||
@interface MP42AACImporter : MP42FileImporter {
|
||||
FILE* inFile;
|
||||
int64_t size;
|
||||
|
||||
NSMutableData *aacInfo;
|
||||
u_int32_t samplesPerSecond;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -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 <assert.h>
|
||||
#include <ctype.h> /* isdigit, isprint, isspace */
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
#include <sys/types.h>
|
||||
#include "mbs.h"
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#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
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// MP42AC3FileImporter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 07/12/10.
|
||||
// Copyright 2010 Damiano Galassi All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42FileImporter.h"
|
||||
|
||||
@interface MP42AC3Importer : MP42FileImporter {
|
||||
FILE* inFile;
|
||||
int64_t size;
|
||||
|
||||
NSMutableData *ac3Info;
|
||||
u_int32_t samplesPerSecond;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -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 <sys/stat.h>
|
||||
|
||||
#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
|
||||
@@ -0,0 +1,18 @@
|
||||
//
|
||||
// MP42MkvFileImporter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/10.
|
||||
// Copyright 2010 Damiano Galassi All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42FileImporter.h"
|
||||
@class AVAsset;
|
||||
|
||||
@interface MP42AVFImporter : MP42FileImporter {
|
||||
AVAsset *_localAsset;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,91 @@
|
||||
//
|
||||
// SBAudioConverter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 16/09/10.
|
||||
// Copyright 2010 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#include "sfifo.h"
|
||||
#include "downmix.h"
|
||||
#import "MP42ConverterProtocol.h"
|
||||
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
#import <CoreAudio/CoreAudio.h>
|
||||
|
||||
@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 <MP42ConverterProtocol> {
|
||||
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
|
||||
@@ -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
|
||||
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// MP42SubtitleTrack.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/09.
|
||||
// Copyright 2009 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42Track.h"
|
||||
|
||||
@interface MP42AudioTrack : MP42Track <NSCoding, NSCopying> {
|
||||
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
|
||||
@@ -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
|
||||
@@ -0,0 +1,53 @@
|
||||
//
|
||||
// SBVobSubConverter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 26/03/11.
|
||||
// Copyright 2011 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "MP42ConverterProtocol.h"
|
||||
#import "MP42Fifo.h"
|
||||
|
||||
#include <avcodec.h>
|
||||
|
||||
@class MP42SampleBuffer;
|
||||
@class MP42SubtitleTrack;
|
||||
@class MP42OCRWrapper;
|
||||
|
||||
@interface MP42BitmapSubConverter : NSObject <MP42ConverterProtocol> {
|
||||
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
|
||||
@@ -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
|
||||
@@ -0,0 +1,15 @@
|
||||
//
|
||||
// MP42CCFileImporter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 05/12/10.
|
||||
// Copyright 2010 Damiano Galassi All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42FileImporter.h"
|
||||
|
||||
@interface MP42CCImporter : MP42FileImporter {
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -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
|
||||
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// MP42ChapterTrack.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 06/02/09.
|
||||
// Copyright 2009 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42Track.h"
|
||||
|
||||
@class SBTextSample;
|
||||
|
||||
@interface MP42ChapterTrack : MP42Track <NSCoding> {
|
||||
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
|
||||
@@ -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
|
||||
@@ -0,0 +1,14 @@
|
||||
//
|
||||
// MP42SubtitleTrack.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/09.
|
||||
// Copyright 2009 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42VideoTrack.h"
|
||||
|
||||
@interface MP42ClosedCaptionTrack : MP42VideoTrack
|
||||
|
||||
@end
|
||||
@@ -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
|
||||
@@ -0,0 +1,26 @@
|
||||
//
|
||||
// MP42ConverterProtocol.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 05/08/13.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42Sample.h"
|
||||
|
||||
@protocol MP42ConverterProtocol <NSObject>
|
||||
|
||||
@optional
|
||||
- (NSData *)magicCookie;
|
||||
|
||||
@required
|
||||
- (void)addSample:(MP42SampleBuffer *)sample;
|
||||
- (MP42SampleBuffer *)copyEncodedSample;
|
||||
|
||||
- (void)cancel;
|
||||
- (BOOL)encoderDone;
|
||||
|
||||
- (void)setInputDone;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,41 @@
|
||||
//
|
||||
// MP42Fifo.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 09/08/13.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@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
|
||||
+103
@@ -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
|
||||
@@ -0,0 +1,67 @@
|
||||
//
|
||||
// MP42File.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/09.
|
||||
// Copyright 2009 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#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 <NSCoding>
|
||||
|
||||
@property(readwrite, assign) id <MP42FileDelegate> 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 <MP42FileDelegate>)del;
|
||||
- (instancetype)initWithExistingFile:(NSURL *)URL andDelegate:(id <MP42FileDelegate>)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
|
||||
+929
@@ -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 <QTKit/QTKit.h>
|
||||
|
||||
#if __MAC_OS_X_VERSION_MAX_ALLOWED > 1060
|
||||
#import <AVFoundation/AVFoundation.h>
|
||||
#endif
|
||||
|
||||
#import "mp4v2.h"
|
||||
|
||||
NSString * const MP42Create64BitData = @"MP4264BitData";
|
||||
NSString * const MP42Create64BitTime = @"MP4264BitTime";
|
||||
NSString * const MP42CreateChaptersPreviewTrack = @"MP42ChaptersPreview";
|
||||
NSString * const MP42OrganizeAlternateGroups = @"MP42AlternateGroups";
|
||||
|
||||
@interface MP42File () <MP42MuxerDelegate> {
|
||||
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 <MP42FileDelegate>)del;
|
||||
{
|
||||
if ((self = [self init])) {
|
||||
_delegate = del;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (instancetype)initWithExistingFile:(NSURL *)URL andDelegate:(id <MP42FileDelegate>)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
|
||||
@@ -0,0 +1,65 @@
|
||||
//
|
||||
// MP42FileImporter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/10.
|
||||
// Copyright 2010 Damiano Galassi All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
|
||||
#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
|
||||
@@ -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
|
||||
@@ -0,0 +1,45 @@
|
||||
//
|
||||
// MP42H264FileImporter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 07/12/10.
|
||||
// Copyright 2010 Damiano Galassi All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,64 @@
|
||||
//
|
||||
// SBHtmlParser.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 13/06/13.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#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
|
||||
@@ -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
|
||||
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// MP42Image.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 27/06/13.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@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 <NSCoding> {
|
||||
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
|
||||
@@ -0,0 +1,135 @@
|
||||
//
|
||||
// MP42Image.m
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 27/06/13.
|
||||
//
|
||||
//
|
||||
|
||||
#import "MP42Image.h"
|
||||
#import <Quartz/Quartz.h>
|
||||
|
||||
@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
|
||||
@@ -0,0 +1,78 @@
|
||||
//
|
||||
// MP42MediaFormat.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 08/08/13.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/* 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;
|
||||
@@ -0,0 +1,72 @@
|
||||
//
|
||||
// MP42MediaFormat.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 08/08/13.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
// 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";
|
||||
@@ -0,0 +1,70 @@
|
||||
//
|
||||
// MP42Metadata.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 06/02/09.
|
||||
// Copyright 2009 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "MP42MediaFormat.h"
|
||||
|
||||
@interface MP42Metadata : NSObject <NSCoding, NSCopying> {
|
||||
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
|
||||
+1547
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,19 @@
|
||||
//
|
||||
// MP42MkvFileImporter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/10.
|
||||
// Copyright 2010 Damiano Galassi All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42FileImporter.h"
|
||||
|
||||
@interface MP42MkvImporter : MP42FileImporter {
|
||||
struct MatroskaFile *_matroskaFile;
|
||||
struct StdIoStream *_ioStream;
|
||||
|
||||
u_int64_t _fileDuration;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -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
|
||||
@@ -0,0 +1,18 @@
|
||||
//
|
||||
// MP42MkvFileImporter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/10.
|
||||
// Copyright 2010 Damiano Galassi All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42FileImporter.h"
|
||||
#import "MP42File.h"
|
||||
#import "mp4v2.h"
|
||||
|
||||
@interface MP42Mp4Importer : MP42FileImporter <MP42FileDelegate> {
|
||||
MP4FileHandle _fileHandle;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -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
|
||||
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// MP42Muxer.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 30/06/10.
|
||||
// Copyright 2010 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#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 <MP42MuxerDelegate>)del;
|
||||
|
||||
- (void)addTrack:(MP42Track *)track;
|
||||
|
||||
- (BOOL)setup:(MP4FileHandle)fileHandle error:(NSError **)outError;
|
||||
- (void)work;
|
||||
- (void)cancel;
|
||||
|
||||
@end
|
||||
@@ -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 <MP42FileDelegate>)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
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// SBOcr.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 27/03/11.
|
||||
// Copyright 2011 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@interface MP42OCRWrapper : NSObject {
|
||||
void *tess_base;
|
||||
|
||||
NSString *_language;
|
||||
}
|
||||
|
||||
- (instancetype)initWithLanguage:(NSString *)language;
|
||||
- (NSString *)performOCROnCGImage:(CGImageRef)image;
|
||||
|
||||
@end
|
||||
@@ -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
|
||||
@@ -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 <Foundation/Foundation.h>
|
||||
#import "MP42FileImporter.h"
|
||||
#import <QTKit/QTKit.h>
|
||||
|
||||
@interface MP42QTImporter : MP42FileImporter {
|
||||
QTMovie *_sourceFile;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
//
|
||||
// MP42Sample.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 29/06/10.
|
||||
// Copyright 2010 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@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
|
||||
@@ -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
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// MP42MkvFileImporter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/10.
|
||||
// Copyright 2010 Damiano Galassi All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42FileImporter.h"
|
||||
|
||||
@class SBSubSerializer;
|
||||
|
||||
@interface MP42SrtImporter : MP42FileImporter {
|
||||
SBSubSerializer *_ss;
|
||||
|
||||
BOOL _verticalPlacement;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -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
|
||||
@@ -0,0 +1,80 @@
|
||||
//
|
||||
// SubUtilities.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Alexander Strange on 7/24/07.
|
||||
// Copyright 2007 Perian. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <UniversalDetector.h>
|
||||
#import "mp4v2.h"
|
||||
|
||||
@interface SBTextSample : NSObject <NSCoding> {
|
||||
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);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
||||
//
|
||||
// MP42SubtitleTrack.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/09.
|
||||
// Copyright 2009 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42VideoTrack.h"
|
||||
|
||||
@interface MP42SubtitleTrack : MP42VideoTrack <NSCoding> {
|
||||
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
|
||||
@@ -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(@"</font>", sampleText, &index, fontStyles, 0, kTagClose);
|
||||
|
||||
NSString *font = [NSString stringWithFormat:@"<font color=\"#%02x%02x%02x\">", (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(@"<b>", sampleText, &index, fontStyles, kStyleBold, kTagOpen);
|
||||
|
||||
if (record.fontStyles & kStyleItalic && !(*fontStyles & kStyleItalic))
|
||||
insertTag(@"<i>", sampleText, &index, fontStyles, kStyleItalic, kTagOpen);
|
||||
|
||||
if (record.fontStyles & kStyleUnderlined && !(*fontStyles & kStyleUnderlined))
|
||||
insertTag(@"<u>", sampleText, &index, fontStyles, kStyleUnderlined, kTagOpen);
|
||||
|
||||
// Close tag
|
||||
if (!(record.fontStyles & kStyleUnderlined) && *fontStyles & kStyleUnderlined)
|
||||
insertTag(@"</u>", sampleText, &index, fontStyles, kStyleUnderlined, kTagClose);
|
||||
|
||||
if (!(record.fontStyles & kStyleItalic) && *fontStyles & kStyleItalic)
|
||||
insertTag(@"</i>", sampleText, &index, fontStyles, kStyleItalic, kTagClose);
|
||||
|
||||
if (!(record.fontStyles & kStyleBold) && *fontStyles & kStyleBold)
|
||||
insertTag(@"</b>", sampleText, &index, fontStyles, kStyleBold, kStyleColor);
|
||||
|
||||
|
||||
if ((!(record.fontStyles & kStyleColor) && *fontStyles & kStyleColor))
|
||||
insertTag(@"</font>", 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
|
||||
@@ -0,0 +1,93 @@
|
||||
//
|
||||
// MP42Track.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/09.
|
||||
// Copyright 2009 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#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 <MP42ConverterProtocol> converter;
|
||||
MP42Fifo *fifo;
|
||||
|
||||
BOOL done;
|
||||
} muxer_helper;
|
||||
|
||||
@interface MP42Track : NSObject <NSCoding, NSCopying> {
|
||||
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
|
||||
@@ -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
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* MP42Utilities.h
|
||||
* Subler
|
||||
*
|
||||
* Created by Damiano Galassi on 30/01/09.
|
||||
* Copyright 2009 Damiano Galassi. All rights reserved.
|
||||
*
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#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);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,59 @@
|
||||
//
|
||||
// MP42VideoTrack.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/01/09.
|
||||
// Copyright 2009 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42Track.h"
|
||||
|
||||
@interface MP42VideoTrack : MP42Track <NSCoding> {
|
||||
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
|
||||
@@ -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 <mp4v2.h>
|
||||
|
||||
@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
|
||||
@@ -0,0 +1,15 @@
|
||||
//
|
||||
// SBVobSubImpoter.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 20/12/12.
|
||||
//
|
||||
//
|
||||
|
||||
#import "MP42FileImporter.h"
|
||||
|
||||
@interface MP42VobSubImporter : MP42FileImporter {
|
||||
NSArray *_VobSubTracks;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -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
|
||||
@@ -0,0 +1,21 @@
|
||||
//
|
||||
// MP42XMLReader.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 25/01/13.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class MP42Metadata;
|
||||
|
||||
@interface MP42XMLReader : NSObject {
|
||||
MP42Metadata *mMetadata;
|
||||
}
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)url error:(NSError **)error;
|
||||
|
||||
@property(readonly) MP42Metadata *mMetadata;
|
||||
|
||||
@end
|
||||
@@ -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
|
||||
@@ -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 <Foundation/NSArray.h>
|
||||
#import <Foundation/NSError.h>
|
||||
#import <Foundation/NSObjCRuntime.h>
|
||||
#import <Foundation/NSRange.h>
|
||||
#import <Foundation/NSString.h>
|
||||
#endif // __OBJC__
|
||||
|
||||
#include <limits.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
#include <TargetConditionals.h>
|
||||
#include <AvailabilityMacros.h>
|
||||
|
||||
#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
|
||||
+2636
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,49 @@
|
||||
//
|
||||
// SBLanguages.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 13/08/12.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
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
|
||||
@@ -0,0 +1,646 @@
|
||||
//
|
||||
// SBLanguages.m
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 13/08/12.
|
||||
//
|
||||
//
|
||||
|
||||
#import "SBLanguages.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
|
||||
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
|
||||
@@ -0,0 +1,29 @@
|
||||
//
|
||||
// SBRatings.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Douglas Stebila on 2013-06-02.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@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
|
||||
@@ -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
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* MatroskaFile.c
|
||||
* Subler
|
||||
*
|
||||
* Created by Ryan Walklin on 23/09/09.
|
||||
* Copyright 2009 Test Toast. All rights reserved.
|
||||
*
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
#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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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: <http://handbrake.fr/>.
|
||||
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 */
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 <assert.h>
|
||||
#include <ctype.h> /* isdigit, isprint, isspace */
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#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__ */
|
||||
|
||||
@@ -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
|
||||
+147
@@ -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 <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#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;
|
||||
}
|
||||
|
||||
@@ -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 <errno.h>
|
||||
|
||||
/*------------------------------------------------
|
||||
"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
|
||||
Reference in new issue
Block a user