OSDN Git Service

LinGui: make Help->Guide work on windows/mingw
[handbrake-jp/handbrake-jp-git.git] / libhb / decssasub.c
1 /* 
2    This file is part of the HandBrake source code.
3    Homepage: <http://handbrake.fr/>.
4    It may be used under the terms of the GNU General Public License. */
5
6 /*
7  * Converts SSA subtitles to UTF-8 subtitles with limited HTML-style markup (<b>, <i>, <u>).
8  * 
9  * SSA format references:
10  *   http://www.matroska.org/technical/specs/subtitles/ssa.html
11  *   http://moodub.free.fr/video/ass-specs.doc
12  *   vlc-1.0.4/modules/codec/subtitles/subsass.c:ParseSSAString
13  * 
14  * @author David Foster (davidfstr)
15  */
16
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include "hb.h"
20
21 typedef enum {
22     BOLD        = 0x01,
23     ITALIC      = 0x02,
24     UNDERLINE   = 0x04
25 } StyleSet;
26
27 // "<b></b>".len + "<i></i>".len + "<u></u>".len
28 #define MAX_OVERHEAD_PER_OVERRIDE (7 * 3)
29
30 #define SSA_2_HB_TIME(hr,min,sec,centi) \
31     ( 90L * ( hr    * 1000L * 60 * 60 +\
32               min   * 1000L * 60 +\
33               sec   * 1000L +\
34               centi * 10L ) )
35
36 static StyleSet ssa_parse_style_override( uint8_t *pos, StyleSet prevStyles )
37 {
38     StyleSet nextStyles = prevStyles;
39     for (;;)
40     {
41         // Skip over leading '{' or last '\\'
42         pos++;
43         
44         // Scan for next \code
45         while ( *pos != '\\' && *pos != '}' && *pos != '\0' ) pos++;
46         if ( *pos != '\\' )
47         {
48             // End of style override block
49             break;
50         }
51         
52         // If next chars are \[biu][01], interpret it
53         if ( strchr("biu", pos[1]) && strchr("01", pos[2]) )
54         {
55             StyleSet styleID =
56                 pos[1] == 'b' ? BOLD :
57                 pos[1] == 'i' ? ITALIC :
58                 pos[1] == 'u' ? UNDERLINE : 0;
59             int enabled = (pos[2] == '1');
60             
61             if (enabled)
62             {
63                 nextStyles |= styleID;
64             }
65             else
66             {
67                 nextStyles &= ~styleID;
68             }
69         }
70     }
71     return nextStyles;
72 }
73
74 static void ssa_append_html_tags_for_style_change(
75     uint8_t **dst, StyleSet prevStyles, StyleSet nextStyles )
76 {
77     #define APPEND(str) { \
78         char *src = str; \
79         while (*src) { *(*dst)++ = *src++; } \
80     }
81
82     // Reverse-order close all previous styles
83     if (prevStyles & UNDERLINE) APPEND("</u>");
84     if (prevStyles & ITALIC)    APPEND("</i>");
85     if (prevStyles & BOLD)      APPEND("</b>");
86     
87     // Forward-order open all next styles
88     if (nextStyles & BOLD)      APPEND("<b>");
89     if (nextStyles & ITALIC)    APPEND("<i>");
90     if (nextStyles & UNDERLINE) APPEND("<u>");
91     
92     #undef APPEND
93 }
94
95 /*
96  * SSA packet format:
97  *   Dialogue: Marked,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text
98  *             1      2     3   4     5    6       7       8       9      10
99  */
100 static hb_buffer_t *ssa_decode_to_utf8( hb_buffer_t *in )
101 {
102     uint8_t *pos = in->data;
103     uint8_t *end = in->data + in->size;
104     
105     // Store NULL after the end of the buffer to make using sscanf safe
106     hb_buffer_realloc( in, in->size + 1 );
107     in->data[in->size] = '\0';
108     
109     /*
110      * Parse Start and End fields for timing information
111      */
112     int start_hr, start_min, start_sec, start_centi;
113     int   end_hr,   end_min,   end_sec,   end_centi;
114     int numPartsRead = sscanf( (char *) in->data, "%*128[^,],"
115         "%d:%d:%d.%d,"  // Start
116         "%d:%d:%d.%d,", // End
117         &start_hr, &start_min, &start_sec, &start_centi,
118           &end_hr,   &end_min,   &end_sec,   &end_centi );
119     if ( numPartsRead != 8 )
120         goto fail;
121     
122     in->start = SSA_2_HB_TIME(start_hr, start_min, start_sec, start_centi);
123     in->stop  = SSA_2_HB_TIME(  end_hr,   end_min,   end_sec,   end_centi);
124     
125     /*
126      * Advance 'pos' to the beginning of the Text field
127      */
128     int curFieldID = 1;
129     while (pos < end)
130     {
131         if ( *pos++ == ',' )
132         {
133             curFieldID++;
134             if ( curFieldID == 10 ) // Text
135                 break;
136         }
137     }
138     if ( curFieldID != 10 )
139         goto fail;
140     uint8_t *textFieldPos = pos;
141     
142     // Count the number of style overrides in the Text field
143     int numStyleOverrides = 0;
144     while ( pos < end )
145     {
146         if (*pos++ == '{')
147         {
148             numStyleOverrides++;
149         }
150     }
151     
152     int maxOutputSize = (end - textFieldPos) + ((numStyleOverrides + 1) * MAX_OVERHEAD_PER_OVERRIDE);
153     hb_buffer_t *out = hb_buffer_init( maxOutputSize );
154     if ( out == NULL )
155         return NULL;
156     
157     /*
158      * The Text field contains plain text marked up with:
159      * (1) '\n' -> space
160      * (2) '\N' -> newline
161      * (3) curly-brace control codes like '{\k44}' -> empty (strip them)
162      * 
163      * Perform the above conversions and copy it to the output packet
164      */
165     StyleSet prevStyles = 0;
166     uint8_t *dst = out->data;
167     pos = textFieldPos;
168     while ( pos < end )
169     {
170         if ( pos[0] == '\\' && pos[1] == 'n' )
171         {
172             *dst++ = ' ';
173             pos += 2;
174         }
175         else if ( pos[0] == '\\' && pos[1] == 'N' )
176         {
177             *dst++ = '\n';
178             pos += 2;
179         }
180         else if ( pos[0] == '{' )
181         {
182             // Parse SSA style overrides and append appropriate HTML style tags
183             StyleSet nextStyles = ssa_parse_style_override( pos, prevStyles );
184             ssa_append_html_tags_for_style_change( &dst, prevStyles, nextStyles );
185             prevStyles = nextStyles;
186             
187             // Skip past SSA control code
188             while ( pos < end && *pos != '}' ) pos++;
189             if    ( pos < end && *pos == '}' ) pos++;
190         }
191         else
192         {
193             // Copy raw character
194             *dst++ = *pos++;
195         }
196     }
197     
198     // Append closing HTML style tags
199     ssa_append_html_tags_for_style_change( &dst, prevStyles, 0 );
200     
201     // Trim output buffer to the actual amount of data written
202     out->size = dst - out->data;
203     
204     // Copy metadata from the input packet to the output packet
205     out->start = in->start;
206     out->stop = in->stop;
207     
208     return out;
209     
210 fail:
211     hb_log( "decssasub: malformed SSA subtitle packet: %.*s\n", in->size, in->data );
212     return NULL;
213 }
214
215 static int decssaInit( hb_work_object_t * w, hb_job_t * job )
216 {
217     return 0;
218 }
219
220 static int decssaWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
221                         hb_buffer_t ** buf_out )
222 {
223     hb_buffer_t * in = *buf_in;
224     hb_buffer_t * out = NULL;
225     
226     if ( in->size > 0 ) {
227         out = ssa_decode_to_utf8(in);
228     } else {
229         out = hb_buffer_init( 0 );
230     }
231     
232     if ( out != NULL ) {
233         // We shouldn't be storing the extra NULL character,
234         // but the MP4 muxer expects this, unfortunately.
235         if ( out->size > 0 && out->data[out->size - 1] != '\0' ) {
236             // NOTE: out->size remains unchanged
237             hb_buffer_realloc( out, out->size + 1 );
238             out->data[out->size] = '\0';
239         }
240         
241         // If the input packet was non-empty, do not pass through
242         // an empty output packet (even if the subtitle was empty),
243         // as this would be interpreted as an end-of-stream
244         if ( in->size > 0 && out->size == 0 ) {
245             hb_buffer_close(&out);
246         }
247     }
248     
249     // Dispose the input packet, as it is no longer needed
250     hb_buffer_close(&in);
251     
252     *buf_in = NULL;
253     *buf_out = out;
254     return HB_WORK_OK;
255 }
256
257 static void decssaClose( hb_work_object_t * w )
258 {
259     // nothing
260 }
261
262 hb_work_object_t hb_decssasub =
263 {
264     WORK_DECSSASUB,
265     "SSA Subtitle Decoder",
266     decssaInit,
267     decssaWork,
268     decssaClose
269 };