source: trunk/TextSubCodec.c @ 1038

Revision 1038, 18.5 KB checked in by astrange, 5 years ago (diff)

Add LGPL license headers to all files (or MIT where appropriate)
Get rid of "All rights reserved" which is LGPL-incompatible.

I didn't touch the Apple sample code, but they should've taken it out too...

  • Property svn:executable set to *
Line 
1/*
2 * TextSubCodec.c
3 * Created by David Conrad on 3/21/06.
4 *
5 * This file is part of Perian.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#if __MACH__
23    #include <Carbon/Carbon.h>
24    #include <QuickTime/QuickTime.h>
25#else
26    #include <ConditionalMacros.h>
27    #include <Endian.h>
28    #include <ImageCodec.h>
29#endif
30
31#include "TextSubCodec.h"
32#include "SubATSUIRenderer.h"
33
34// Constants
35const UInt8 kNumPixelFormatsSupportedTextSub = 2;
36
37// Data structures
38typedef struct TextSubGlobalsRecord {
39        ComponentInstance               self;
40        ComponentInstance               delegateComponent;
41        ComponentInstance               target;
42        OSType**                                wantedDestinationPixelTypeH;
43        ImageCodecMPDrawBandUPP drawBandUPP;
44       
45        CGColorSpaceRef         colorSpace;
46
47        SubtitleRendererPtr             ssa;
48        Boolean                                 translateSRT;
49} TextSubGlobalsRecord, *TextSubGlobals;
50
51typedef struct {
52        long            width;
53        long            height;
54        long            depth;
55    long        dataSize;
56   
57    Ptr             baseAddr;
58        OSType                  pixelFormat;
59} TextSubDecompressRecord;
60
61// Setup required for ComponentDispatchHelper.c
62#define IMAGECODEC_BASENAME()           TextSubCodec
63#define IMAGECODEC_GLOBALS()            TextSubGlobals storage
64
65#define CALLCOMPONENT_BASENAME()        IMAGECODEC_BASENAME()
66#define CALLCOMPONENT_GLOBALS()         IMAGECODEC_GLOBALS()
67
68#define COMPONENT_UPP_PREFIX()          uppImageCodec
69#define COMPONENT_DISPATCH_FILE         "TextSubCodecDispatch.h"
70#define COMPONENT_SELECT_PREFIX()       kImageCodec
71
72#define GET_DELEGATE_COMPONENT()        (storage->delegateComponent)
73
74
75#if __MACH__
76        #include <CoreServices/Components.k.h>
77        #include <QuickTime/ImageCodec.k.h>
78        #include <QuickTime/ComponentDispatchHelper.c>
79#else
80        #include <Components.k.h>
81        #include <ImageCodec.k.h>
82        #include <ComponentDispatchHelper.c>
83#endif
84       
85static CFMutableStringRef CFStringCreateMutableWithBytes(CFAllocatorRef alloc, char *cStr, size_t size, CFStringEncoding encoding) {
86        CFStringRef                s1 = CFStringCreateWithBytes(alloc,(UInt8*)cStr,size,encoding,false);
87        if (!s1) return NULL;
88        CFMutableStringRef s2 = CFStringCreateMutableCopy(alloc,0,s1);
89        CFRelease(s1);
90        return s2;
91}
92
93/* -- This Image Decompressor Uses the Base Image Decompressor Component --
94        The base image decompressor is an Apple-supplied component
95        that makes it easier for developers to create new decompressors.
96        The base image decompressor does most of the housekeeping and
97        interface functions required for a QuickTime decompressor component,
98        including scheduling for asynchronous decompression.
99*/
100
101// Component Open Request - Required
102pascal ComponentResult TextSubCodecOpen(TextSubGlobals glob, ComponentInstance self)
103{
104        ComponentResult err;
105
106        // Allocate memory for our globals, set them up and inform the component manager that we've done so
107        glob = (TextSubGlobals)NewPtrClear(sizeof(TextSubGlobalsRecord));
108        if (err = MemError()) goto bail;
109
110        SetComponentInstanceStorage(self, (Handle)glob);
111
112        glob->self = self;
113        glob->target = self;
114        glob->wantedDestinationPixelTypeH = (OSType **)NewHandle(sizeof(OSType) * (kNumPixelFormatsSupportedTextSub + 1));
115        if (err = MemError()) goto bail;
116        glob->drawBandUPP = NULL;
117        glob->ssa = NULL;
118        glob->colorSpace = NULL;
119       
120        // Open and target an instance of the base decompressor as we delegate
121        // most of our calls to the base decompressor instance
122        err = OpenADefaultComponent(decompressorComponentType, kBaseCodecType, &glob->delegateComponent);
123        if (err) goto bail;
124
125        ComponentSetTarget(glob->delegateComponent, self);
126
127bail:
128        return err;
129}
130
131// Component Close Request - Required
132pascal ComponentResult TextSubCodecClose(TextSubGlobals glob, ComponentInstance self)
133{
134        // Make sure to close the base component and dealocate our storage
135        if (glob) {
136                if (glob->delegateComponent) {
137                        CloseComponent(glob->delegateComponent);
138                }
139                if (glob->wantedDestinationPixelTypeH) {
140                        DisposeHandle((Handle)glob->wantedDestinationPixelTypeH);
141                }
142                if (glob->drawBandUPP) {
143                        DisposeImageCodecMPDrawBandUPP(glob->drawBandUPP);
144                }
145                if (glob->colorSpace) {
146                        CGColorSpaceRelease(glob->colorSpace);
147                }
148                if (glob->ssa) SubDisposeRenderer(glob->ssa);
149                DisposePtr((Ptr)glob);
150        }
151
152        return noErr;
153}
154
155// Component Version Request - Required
156pascal ComponentResult TextSubCodecVersion(TextSubGlobals glob)
157{
158#pragma unused(glob)
159       
160    return kTextSubCodecVersion;
161}
162
163// Component Target Request
164//              Allows another component to "target" you i.e., you call another component whenever
165// you would call yourself (as a result of your component being used by another component)
166pascal ComponentResult TextSubCodecTarget(TextSubGlobals glob, ComponentInstance target)
167{
168        glob->target = target;
169        return noErr;
170}
171
172// Component GetMPWorkFunction Request
173//              Allows your image decompressor component to perform asynchronous decompression
174// in a single MP task by taking advantage of the Base Decompressor. If you implement
175// this selector, your DrawBand function must be MP-safe. MP safety means not
176// calling routines that may move or purge memory and not calling any routines which
177// might cause 68K code to be executed.
178pascal ComponentResult TextSubCodecGetMPWorkFunction(TextSubGlobals glob, ComponentMPWorkFunctionUPP *workFunction, void **refCon)
179{
180        if (NULL == glob->drawBandUPP)
181                glob->drawBandUPP = NewImageCodecMPDrawBandUPP((ImageCodecMPDrawBandProcPtr)TextSubCodecDrawBand);
182               
183        return ImageCodecGetBaseMPWorkFunction(glob->delegateComponent, workFunction, refCon, glob->drawBandUPP, glob);
184}
185
186#pragma mark-
187
188// ImageCodecInitialize
189//              The first function call that your image decompressor component receives from the base image
190// decompressor is always a call to ImageCodecInitialize . In response to this call, your image decompressor
191// component returns an ImageSubCodecDecompressCapabilities structure that specifies its capabilities.
192pascal ComponentResult TextSubCodecInitialize(TextSubGlobals glob, ImageSubCodecDecompressCapabilities *cap)
193{
194#pragma unused(glob)
195
196        // Secifies the size of the ImageSubCodecDecompressRecord structure
197        // and say we can support asyncronous decompression
198        // With the help of the base image decompressor, any image decompressor
199        // that uses only interrupt-safe calls for decompression operations can
200        // support asynchronous decompression.
201        cap->decompressRecordSize = sizeof(TextSubDecompressRecord);
202        cap->canAsync = true;
203       
204        cap->subCodecIsMultiBufferAware = true;
205        cap->subCodecSupportsDecodeSmoothing = true;
206
207        return noErr;
208}
209
210// ImageCodecPreflight
211//              The base image decompressor gets additional information about the capabilities of your image
212// decompressor component by calling ImageCodecPreflight. The base image decompressor uses this
213// information when responding to a call to the ImageCodecPredecompress function,
214// which the ICM makes before decompressing an image. You are required only to provide values for
215// the wantedDestinationPixelSize and wantedDestinationPixelTypes fields and can also modify other
216// fields if necessary.
217pascal ComponentResult TextSubCodecPreflight(TextSubGlobals glob, CodecDecompressParams *p)
218{
219        CodecCapabilities *capabilities = p->capabilities;
220        OSTypePtr         formats = *glob->wantedDestinationPixelTypeH;
221
222        // Fill in formats for wantedDestinationPixelTypeH
223        // Terminate with an OSType value 0  - see IceFloe #7
224        // http://developer.apple.com/quicktime/icefloe/dispatch007.html
225   
226    // we want ARGB because Quartz can use it easily
227    // Todo: add other possible pixel formats Quartz can handle
228    *formats++  = k32RGBAPixelFormat;
229        *formats++      = k32ARGBPixelFormat;
230        *formats++      = 0;
231       
232        // Specify the minimum image band height supported by the component
233        // bandInc specifies a common factor of supported image band heights -
234        // if your component supports only image bands that are an even
235    // multiple of some number of pixels high report this common factor in bandInc
236        capabilities->bandMin = (**p->imageDescription).height;
237        capabilities->bandInc = capabilities->bandMin;
238
239        // Indicate the wanted destination using the wantedDestinationPixelTypeH previously set up
240        capabilities->wantedPixelSize  = 0;     
241   
242        p->wantedDestinationPixelTypes = glob->wantedDestinationPixelTypeH;
243
244        // Specify the number of pixels the image must be extended in width and height if
245        // the component cannot accommodate the image at its given width and height
246        capabilities->extendWidth = 0;
247        capabilities->extendHeight = 0;
248       
249        capabilities->flags |= codecCanAsync | codecCanAsyncWhen | codecCanScale;
250        capabilities->flags2 |= codecDrawsHigherQualityScaled;
251   
252        glob->colorSpace = NULL;
253        glob->translateSRT = true;
254        glob->ssa = NULL;
255       
256        if (!glob->ssa) {
257                if ((**p->imageDescription).cType == kSubFormatSSA) {
258                        long count;
259                        glob->translateSRT = false;
260                       
261                        CountImageDescriptionExtensionType(p->imageDescription,kSubFormatSSA,&count);
262                        if (count == 1) {
263                                Handle ssaheader;
264                                GetImageDescriptionExtension(p->imageDescription,&ssaheader,kSubFormatSSA,1);
265                               
266                                glob->ssa = SubInitForSSA(*ssaheader, GetHandleSize(ssaheader), (**p->imageDescription).width, (**p->imageDescription).height);
267                        } 
268                } 
269               
270                if (!glob->ssa) glob->ssa = SubInitNonSSA((**p->imageDescription).width,(**p->imageDescription).height);
271                               
272                glob->colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
273        }
274       
275        return noErr;
276}
277
278// ImageCodecBeginBand
279//              The ImageCodecBeginBand function allows your image decompressor component to save information about
280// a band before decompressing it. This function is never called at interrupt time. The base image decompressor
281// preserves any changes your component makes to any of the fields in the ImageSubCodecDecompressRecord
282// or CodecDecompressParams structures. If your component supports asynchronous scheduled decompression, it
283// may receive more than one ImageCodecBeginBand call before receiving an ImageCodecDrawBand call.
284pascal ComponentResult TextSubCodecBeginBand(TextSubGlobals glob, CodecDecompressParams *p, ImageSubCodecDecompressRecord *drp, long flags)
285{
286        TextSubDecompressRecord *myDrp = (TextSubDecompressRecord *)drp->userDecompressRecord;
287       
288        // Let base codec know that all our frames are key frames (a.k.a., sync samples)
289        // This allows the base codec to perform frame dropping on our behalf if needed
290    drp->frameType = kCodecFrameTypeKey;
291
292        myDrp->pixelFormat = p->dstPixMap.pixelFormat;
293        myDrp->width = p->dstRect.right - p->dstRect.left;
294        myDrp->height = p->dstRect.bottom - p->dstRect.top;
295        myDrp->depth = (**p->imageDescription).depth;
296    myDrp->dataSize = p->bufferSize;
297       
298        return noErr;
299}
300
301// ImageCodecDrawBand
302//              The base image decompressor calls your image decompressor component's ImageCodecDrawBand function
303// to decompress a band or frame. Your component must implement this function. If the ImageSubCodecDecompressRecord
304// structure specifies a progress function or data-loading function, the base image decompressor will never call ImageCodecDrawBand
305// at interrupt time. If the ImageSubCodecDecompressRecord structure specifies a progress function, the base image decompressor
306// handles codecProgressOpen and codecProgressClose calls, and your image decompressor component must not implement these functions.
307// If not, the base image decompressor may call the ImageCodecDrawBand function at interrupt time.
308// When the base image decompressor calls your ImageCodecDrawBand function, your component must perform the decompression specified
309// by the fields of the ImageSubCodecDecompressRecord structure. The structure includes any changes your component made to it
310// when performing the ImageCodecBeginBand function. If your component supports asynchronous scheduled decompression,
311// it may receive more than one ImageCodecBeginBand call before receiving an ImageCodecDrawBand call.
312pascal ComponentResult TextSubCodecDrawBand(TextSubGlobals glob, ImageSubCodecDecompressRecord *drp)
313{
314        TextSubDecompressRecord *myDrp = (TextSubDecompressRecord *)drp->userDecompressRecord;
315        CGImageAlphaInfo alphaFormat = (myDrp->pixelFormat == k32ARGBPixelFormat) ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaPremultipliedLast;
316
317    CGContextRef c = CGBitmapContextCreate(drp->baseAddr, myDrp->width, myDrp->height,
318                                                                                   8, drp->rowBytes,  glob->colorSpace,
319                                                                                   alphaFormat);
320       
321        CGContextClearRect(c, CGRectMake(0,0, myDrp->width, myDrp->height));
322       
323        CFMutableStringRef buf;
324       
325        if (drp->codecData[0] == '\n' && myDrp->dataSize == 1) goto leave; // skip empty packets
326       
327        if (glob->translateSRT) {
328                buf = CFStringCreateMutableWithBytes(NULL, drp->codecData, myDrp->dataSize, kCFStringEncodingUTF8);
329                if (!buf) goto leave;
330                CFStringFindAndReplace(buf, CFSTR("<i>"),  CFSTR("{\\i1}"), CFRangeMake(0,CFStringGetLength(buf)), 0);
331                CFStringFindAndReplace(buf, CFSTR("</i>"), CFSTR("{\\i0}"), CFRangeMake(0,CFStringGetLength(buf)), 0);
332                CFStringFindAndReplace(buf, CFSTR("<"),    CFSTR("{"),      CFRangeMake(0,CFStringGetLength(buf)), 0);
333                CFStringFindAndReplace(buf, CFSTR(">"),    CFSTR("}"),      CFRangeMake(0,CFStringGetLength(buf)), 0);
334        } else {
335                buf = (CFMutableStringRef)CFStringCreateWithBytes(NULL, (UInt8*)drp->codecData, myDrp->dataSize, kCFStringEncodingUTF8, false);
336                if (!buf) goto leave;
337        }
338       
339        SubRenderPacket(glob->ssa,c,buf,myDrp->width,myDrp->height);
340       
341#if 0
342        {
343                CFURLRef url = CFURLCreateFromFileSystemRepresentation(NULL, "/subtitle.pdf", strlen("/subtitle.pdf"), 0);
344                CGRect rect = CGRectMake(0,0, myDrp->width, myDrp->height);
345                CGContextRef pc = CGPDFContextCreateWithURL(url, &rect, NULL);
346               
347                CGPDFContextBeginPage(pc, NULL);
348                SubRenderPacket(glob->ssa,pc,buf,myDrp->width,myDrp->height);
349                CGPDFContextEndPage(pc);
350                CGContextRelease(pc);
351                CFRelease(url);
352        }
353#endif
354       
355        CFRelease(buf);
356       
357leave:
358        CGContextRelease(c);
359        return noErr;
360}
361
362// ImageCodecEndBand
363//              The ImageCodecEndBand function notifies your image decompressor component that decompression of a band has finished or
364// that it was terminated by the Image Compression Manager. Your image decompressor component is not required to implement
365// the ImageCodecEndBand function. The base image decompressor may call the ImageCodecEndBand function at interrupt time.
366// After your image decompressor component handles an ImageCodecEndBand call, it can perform any tasks that are required
367// when decompression is finished, such as disposing of data structures that are no longer needed. Because this function
368// can be called at interrupt time, your component cannot use this function to dispose of data structures; this
369// must occur after handling the function. The value of the result parameter should be set to noErr if the band or frame was
370// drawn successfully. If it is any other value, the band or frame was not drawn.
371pascal ComponentResult TextSubCodecEndBand(TextSubGlobals glob, ImageSubCodecDecompressRecord *drp, OSErr result, long flags)
372{
373#pragma unused(glob, drp,result, flags)
374       
375        return noErr;
376}
377
378// ImageCodecQueueStarting
379//              If your component supports asynchronous scheduled decompression, the base image decompressor calls your image decompressor component's
380// ImageCodecQueueStarting function before decompressing the frames in the queue. Your component is not required to implement this function.
381// It can implement the function if it needs to perform any tasks at this time, such as locking data structures.
382// The base image decompressor never calls the ImageCodecQueueStarting function at interrupt time.
383pascal ComponentResult TextSubCodecQueueStarting(TextSubGlobals glob)
384{
385#pragma unused(glob)
386       
387        return noErr;
388}
389
390// ImageCodecQueueStopping
391//               If your image decompressor component supports asynchronous scheduled decompression, the ImageCodecQueueStopping function notifies
392// your component that the frames in the queue have been decompressed. Your component is not required to implement this function.
393// After your image decompressor component handles an ImageCodecQueueStopping call, it can perform any tasks that are required when decompression
394// of the frames is finished, such as disposing of data structures that are no longer needed.
395// The base image decompressor never calls the ImageCodecQueueStopping function at interrupt time.
396pascal ComponentResult TextSubCodecQueueStopping(TextSubGlobals glob)
397{
398#pragma unused(glob)
399       
400        return noErr;
401}
402
403// ImageCodecGetCompressedImageSize
404//              Your component receives the ImageCodecGetCompressedImageSize request whenever an application calls the ICM's GetCompressedImageSize function.
405// You can use the ImageCodecGetCompressedImageSize function when you are extracting a single image from a sequence; therefore, you don't have an
406// image description structure and don't know the exact size of one frame. In this case, the Image Compression Manager calls the component to determine
407// the size of the data. Your component should return a long integer indicating the number of bytes of data in the compressed image. You may want to store
408// the image size somewhere in the image description structure, so that you can respond to this request quickly. Only decompressors receive this request.
409pascal ComponentResult TextSubCodecGetCompressedImageSize(TextSubGlobals glob, ImageDescriptionHandle desc, Ptr data, long dataSize, ICMDataProcRecordPtr dataProc, long *size)
410{
411#pragma unused(glob,dataProc,desc)
412        if (size == NULL) 
413                return paramErr;
414
415//      *size = EndianU32_BtoN(dataSize);
416
417        return noErr;
418}
419
420// ImageCodecGetCodecInfo
421//              Your component receives the ImageCodecGetCodecInfo request whenever an application calls the Image Compression Manager's GetCodecInfo function.
422// Your component should return a formatted compressor information structure defining its capabilities.
423// Both compressors and decompressors may receive this request.
424pascal ComponentResult TextSubCodecGetCodecInfo(TextSubGlobals glob, CodecInfo *info)
425{
426        OSErr err = noErr;
427        ComponentDescription desc;
428        short resid;
429       
430        GetComponentInfo((Component)glob->self, &desc, 0, 0, 0);
431       
432        if (desc.componentSubType == kSubFormatSSA)
433                resid = kSSASubCodecResource;
434        else
435                resid = kTextSubCodecResource;
436
437        if (info == NULL) {
438                err = paramErr;
439        } else {
440                CodecInfo **tempCodecInfo;
441
442                err = GetComponentResource((Component)glob->self, codecInfoResourceType, resid, (Handle *)&tempCodecInfo);
443                if (err == noErr) {
444                        *info = **tempCodecInfo;
445                        DisposeHandle((Handle)tempCodecInfo);
446                }
447        }
448
449        return err;
450}
Note: See TracBrowser for help on using the repository browser.