OSDN Git Service

fix a crash when ass_render_frame doesn't return a frame list.
[handbrake-jp/handbrake-jp-git.git] / libhb / muxmkv.c
1 /* $Id:  $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 /* libmkv header */
8 #include "libmkv.h"
9
10 #include <ogg/ogg.h>
11
12 #include "hb.h"
13
14 /* Scale factor to apply to timecodes to convert from HandBrake's
15  * 1/90000s to nanoseconds as expected by libmkv */
16 #define TIMECODE_SCALE 1000000000 / 90000
17
18 struct hb_mux_object_s
19 {
20     HB_MUX_COMMON;
21
22     hb_job_t * job;
23
24     mk_Writer * file;
25 };
26
27 struct hb_mux_data_s
28 {
29     mk_Track  * track;
30     uint64_t  prev_chapter_tc;
31     uint16_t  current_chapter;
32     int       codec;
33     int       subtitle;
34     int       sub_format;
35 };
36
37 /**********************************************************************
38  * MKVInit
39  **********************************************************************
40  * Allocates hb_mux_data_t structures, create file and write headers
41  *********************************************************************/
42 static int MKVInit( hb_mux_object_t * m )
43 {
44     hb_job_t   * job   = m->job;
45     hb_title_t * title = job->title;
46     hb_audio_t    * audio;
47     hb_mux_data_t * mux_data;
48
49     uint8_t         *avcC = NULL;
50     uint8_t         default_track_flag = 1;
51     int             avcC_len, i, j;
52     ogg_packet      *ogg_headers[3];
53     mk_TrackConfig *track;
54
55     track = calloc(1, sizeof(mk_TrackConfig));
56
57     m->file = mk_createWriter(job->file, 1000000, 1);
58
59     if( !m->file )
60     {
61         hb_error( "Could not create output file, Disk Full?" );
62         job->mux_data = NULL;
63         *job->die = 1;
64         return 0;
65     }
66
67     /* Video track */
68     mux_data      = calloc(1, sizeof( hb_mux_data_t ) );
69     job->mux_data = mux_data;
70
71     track->trackType = MK_TRACK_VIDEO;
72     track->flagDefault = 1;
73     track->flagEnabled = 1;
74     switch (job->vcodec)
75     {
76         case HB_VCODEC_X264:
77             track->codecID = MK_VCODEC_MP4AVC;
78             /* Taken from x264 muxers.c */
79             avcC_len = 5 + 1 + 2 + job->config.h264.sps_length + 1 + 2 + job->config.h264.pps_length;
80             avcC = malloc(avcC_len);
81             if (avcC == NULL)
82                 return -1;
83
84             avcC[0] = 1;
85             avcC[1] = job->config.h264.sps[1];      /* AVCProfileIndication */
86             avcC[2] = job->config.h264.sps[2];      /* profile_compat */
87             avcC[3] = job->config.h264.sps[3];      /* AVCLevelIndication */
88             avcC[4] = 0xff; // nalu size length is four bytes
89             avcC[5] = 0xe1; // one sps
90
91             avcC[6] = job->config.h264.sps_length >> 8;
92             avcC[7] = job->config.h264.sps_length;
93
94             memcpy(avcC+8, job->config.h264.sps, job->config.h264.sps_length);
95
96             avcC[8+job->config.h264.sps_length] = 1; // one pps
97             avcC[9+job->config.h264.sps_length] = job->config.h264.pps_length >> 8;
98             avcC[10+job->config.h264.sps_length] = job->config.h264.pps_length;
99
100             memcpy( avcC+11+job->config.h264.sps_length, job->config.h264.pps, job->config.h264.pps_length );
101             track->codecPrivate = avcC;
102             track->codecPrivateSize = avcC_len;
103             if (job->areBframes)
104                 track->minCache = 1;
105             break;
106         case HB_VCODEC_FFMPEG:
107             track->codecID = MK_VCODEC_MP4ASP;
108             track->codecPrivate = job->config.mpeg4.bytes;
109             track->codecPrivateSize = job->config.mpeg4.length;
110             break;
111         case HB_VCODEC_THEORA:
112             {
113                 int i;
114                 uint64_t cp_size = 0;
115                 track->codecID = MK_VCODEC_THEORA;
116                 uint64_t  header_sizes[3];
117                 for (i = 0; i < 3; ++i)
118                 {
119                     ogg_headers[i] = (ogg_packet *)job->config.theora.headers[i];
120                     ogg_headers[i]->packet = (unsigned char *)&job->config.theora.headers[i] + sizeof( ogg_packet );
121                     header_sizes[i] = ogg_headers[i]->bytes;
122                 }
123                 track->codecPrivate = mk_laceXiph(header_sizes, 2, &cp_size);
124                 track->codecPrivate = realloc(track->codecPrivate, cp_size + ogg_headers[0]->bytes + ogg_headers[1]->bytes + ogg_headers[2]->bytes);
125                 for(i = 0; i < 3; ++i)
126                 {
127                     memcpy(track->codecPrivate + cp_size, ogg_headers[i]->packet, ogg_headers[i]->bytes);
128                     cp_size += ogg_headers[i]->bytes;
129                 }
130                 track->codecPrivateSize = cp_size;
131             }
132             break;
133         default:
134             *job->die = 1;
135             hb_error("muxmkv: Unknown video codec: %x", job->vcodec);
136             return 0;
137     }
138
139     track->extra.video.pixelWidth = job->width;
140     track->extra.video.pixelHeight = job->height;
141     track->extra.video.displayHeight = job->height;
142     if( job->anamorphic.mode )
143     {
144         track->extra.video.displayWidth = job->width * ((double)job->anamorphic.par_width / (double)job->anamorphic.par_height);
145     }
146     else
147     {
148         track->extra.video.displayWidth = job->width;
149     }
150
151
152     track->defaultDuration = (int64_t)(((float)job->vrate_base / (float)job->vrate) * 1000000000);
153
154     mux_data->track = mk_createTrack(m->file, track);
155
156     memset(track, 0, sizeof(mk_TrackConfig));
157
158     /* add the audio tracks */
159     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
160     {
161         audio = hb_list_item( title->list_audio, i );
162         mux_data = calloc(1, sizeof( hb_mux_data_t ) );
163         audio->priv.mux_data = mux_data;
164
165         mux_data->codec = audio->config.out.codec;
166
167         switch (audio->config.out.codec)
168         {
169             case HB_ACODEC_DCA:
170                 track->codecPrivate = NULL;
171                 track->codecPrivateSize = 0;
172                 track->codecID = MK_ACODEC_DTS;
173                 break;
174             case HB_ACODEC_AC3:
175                 track->codecPrivate = NULL;
176                 track->codecPrivateSize = 0;
177                 track->codecID = MK_ACODEC_AC3;
178                 break;
179             case HB_ACODEC_LAME:
180                 track->codecPrivate = NULL;
181                 track->codecPrivateSize = 0;
182                 track->codecID = MK_ACODEC_MP3;
183                 break;
184             case HB_ACODEC_VORBIS:
185                 {
186                     int i;
187                     uint64_t cp_size = 0;
188                     track->codecID = MK_ACODEC_VORBIS;
189                     uint64_t  header_sizes[3];
190                     for (i = 0; i < 3; ++i)
191                     {
192                         ogg_headers[i] = (ogg_packet *)audio->priv.config.vorbis.headers[i];
193                         ogg_headers[i]->packet = (unsigned char *)&audio->priv.config.vorbis.headers[i] + sizeof( ogg_packet );
194                         header_sizes[i] = ogg_headers[i]->bytes;
195                     }
196                     track->codecPrivate = mk_laceXiph(header_sizes, 2, &cp_size);
197                     track->codecPrivate = realloc(track->codecPrivate, cp_size + ogg_headers[0]->bytes + ogg_headers[1]->bytes + ogg_headers[2]->bytes);
198                     for(i = 0; i < 3; ++i)
199                     {
200                         memcpy(track->codecPrivate + cp_size, ogg_headers[i]->packet, ogg_headers[i]->bytes);
201                         cp_size += ogg_headers[i]->bytes;
202                     }
203                     track->codecPrivateSize = cp_size;
204                 }
205                 break;
206             case HB_ACODEC_FAAC:
207             case HB_ACODEC_CA_AAC:
208                 track->codecPrivate = audio->priv.config.aac.bytes;
209                 track->codecPrivateSize = audio->priv.config.aac.length;
210                 track->codecID = MK_ACODEC_AAC;
211                 break;
212             default:
213                 *job->die = 1;
214                 hb_error("muxmkv: Unknown audio codec: %x", audio->config.out.codec);
215                 return 0;
216         }
217
218         if (default_track_flag)
219         {
220             track->flagDefault = 1;
221             default_track_flag = 0;
222         }
223         else
224         {
225             track->flagDefault = 0;
226         }
227         track->flagEnabled = 1;
228         track->trackType = MK_TRACK_AUDIO;
229         track->language = audio->config.lang.iso639_2;
230         track->extra.audio.samplingFreq = (float)audio->config.out.samplerate;
231         if (audio->config.out.codec == HB_ACODEC_AC3 ||
232             audio->config.out.codec == HB_ACODEC_DCA)
233         {
234             track->extra.audio.channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(audio->config.in.channel_layout);
235         }
236         else
237         {
238             track->extra.audio.channels = HB_AMIXDOWN_GET_DISCRETE_CHANNEL_COUNT(audio->config.out.mixdown);
239         }
240 //        track->defaultDuration = job->arate * 1000;
241         mux_data->track = mk_createTrack(m->file, track);
242         if (audio->config.out.codec == HB_ACODEC_VORBIS && track->codecPrivate != NULL)
243           free(track->codecPrivate);
244     }
245
246     char * subidx_fmt =
247         "size: %dx%d\n"
248         "org: %d, %d\n"
249         "scale: 100%%, 100%%\n"
250         "alpha: 100%%\n"
251         "smooth: OFF\n"
252         "fadein/out: 50, 50\n"
253         "align: OFF at LEFT TOP\n"
254         "time offset: 0\n"
255         "forced subs: %s\n"
256         "palette: %06x, %06x, %06x, %06x, %06x, %06x, "
257         "%06x, %06x, %06x, %06x, %06x, %06x, %06x, %06x, %06x, %06x\n"
258         "custom colors: OFF, tridx: 0000, "
259         "colors: 000000, 000000, 000000, 000000\n";
260
261     for( i = 0; i < hb_list_count( title->list_subtitle ); i++ )
262     {
263         hb_subtitle_t * subtitle;
264         uint32_t        rgb[16];
265         char            subidx[2048];
266         int             len;
267
268         subtitle = hb_list_item( title->list_subtitle, i );
269         if (subtitle->config.dest != PASSTHRUSUB)
270             continue;
271
272         memset(track, 0, sizeof(mk_TrackConfig));
273         switch (subtitle->format)
274         {
275             case PICTURESUB:
276                 track->codecID = MK_SUBTITLE_VOBSUB;
277                 for (j = 0; j < 16; j++)
278                     rgb[j] = hb_yuv2rgb(subtitle->palette[j]);
279                 len = snprintf(subidx, 2048, subidx_fmt, 
280                         subtitle->width, subtitle->height,
281                         0, 0, "OFF",
282                         rgb[0], rgb[1], rgb[2], rgb[3],
283                         rgb[4], rgb[5], rgb[6], rgb[7],
284                         rgb[8], rgb[9], rgb[10], rgb[11],
285                         rgb[12], rgb[13], rgb[14], rgb[15]);
286                 track->codecPrivate = subidx;
287                 track->codecPrivateSize = len + 1;
288                 break;
289             case TEXTSUB:
290                 track->codecID = MK_SUBTITLE_UTF8;
291                 break;
292             default:
293                 continue;
294         }
295         if ( subtitle->config.default_track )
296         {
297             track->flagDefault = 1;
298         }
299
300         mux_data = calloc(1, sizeof( hb_mux_data_t ) );
301         subtitle->mux_data = mux_data;
302         mux_data->subtitle = 1;
303         mux_data->sub_format = subtitle->format;
304         
305         track->flagEnabled = 1;
306         track->trackType = MK_TRACK_SUBTITLE;
307         track->language = subtitle->iso639_2;
308
309         mux_data->track = mk_createTrack(m->file, track);
310     }
311
312     if( mk_writeHeader( m->file, "HandBrake " HB_PROJECT_VERSION) < 0 )
313     {
314         hb_error( "Failed to write to output file, disk full?");
315         *job->die = 1;
316     }
317     if (track != NULL)
318         free(track);
319     if (avcC != NULL)
320         free(avcC);
321
322     return 0;
323 }
324
325 static int MKVMux( hb_mux_object_t * m, hb_mux_data_t * mux_data,
326                    hb_buffer_t * buf )
327 {
328     ogg_packet  *op = NULL;
329     hb_job_t * job = m->job;
330     hb_title_t * title = job->title;
331     uint64_t   timecode = 0;
332     hb_chapter_t *chapter_data;
333     char tmp_buffer[1024];
334     char *string = tmp_buffer;
335
336     if (mux_data == job->mux_data)
337     {
338         /* Video */
339         timecode = buf->start * TIMECODE_SCALE;
340
341         if (job->chapter_markers && (buf->new_chap || timecode == 0))
342         {
343             /* Make sure we're not writing a chapter that has 0 length */
344             if (mux_data->prev_chapter_tc != timecode)
345             {
346                 if ( buf->new_chap )
347                 {
348                     mux_data->current_chapter = buf->new_chap - 2;
349                 }
350                 chapter_data = hb_list_item( title->list_chapter,
351                                              mux_data->current_chapter++ );
352                 tmp_buffer[0] = '\0';
353
354                 if( chapter_data != NULL )
355                 {
356                     string = chapter_data->title;
357                 }
358
359                 if( strlen(string) == 0 || strlen(string) >= 1024 )
360                 {
361                     snprintf( tmp_buffer, 1023, "Chapter %02i", mux_data->current_chapter );
362                     string = tmp_buffer;
363                 }
364                 mk_createChapterSimple(m->file, mux_data->prev_chapter_tc, mux_data->prev_chapter_tc, string);
365             }
366             mux_data->prev_chapter_tc = timecode;
367         }
368
369         if (job->vcodec == HB_VCODEC_THEORA)
370         {
371             /* ughhh, theora is a pain :( */
372             op = (ogg_packet *)buf->data;
373             op->packet = buf->data + sizeof( ogg_packet );
374             if (mk_startFrame(m->file, mux_data->track) < 0)
375             {
376                 hb_error( "Failed to write frame to output file, Disk Full?" );
377                 *job->die = 1;
378             }
379             mk_addFrameData(m->file, mux_data->track, op->packet, op->bytes);
380             mk_setFrameFlags(m->file, mux_data->track, timecode, 1, 0);
381             hb_buffer_close( &buf );
382             return 0;
383         }
384     }
385     else if ( mux_data->subtitle )
386     {
387         uint64_t   duration;
388         timecode = buf->start * TIMECODE_SCALE;
389         if( mk_startFrame(m->file, mux_data->track) < 0)
390         {
391             hb_error( "Failed to write frame to output file, Disk Full?" );
392             *job->die = 1;
393         }
394
395         duration = buf->stop * TIMECODE_SCALE - timecode;
396         if( mux_data->sub_format == TEXTSUB )
397         {
398             mk_addFrameData(m->file, mux_data->track, buf->data, buf->size);
399             mk_setFrameFlags(m->file, mux_data->track, timecode, 1, duration);
400         }
401         else
402         {
403             mk_addFrameData(m->file, mux_data->track, buf->data, buf->size);
404             mk_setFrameFlags(m->file, mux_data->track, timecode, 1, duration);
405         }
406         mk_flushFrame(m->file, mux_data->track);
407         hb_buffer_close( &buf );
408         return 0;
409     }
410     else
411     {
412         /* Audio */
413         timecode = buf->start * TIMECODE_SCALE;
414         if (mux_data->codec == HB_ACODEC_VORBIS)
415         {
416             /* ughhh, vorbis is a pain :( */
417             op = (ogg_packet *)buf->data;
418             op->packet = buf->data + sizeof( ogg_packet );
419             if (mk_startFrame(m->file, mux_data->track))
420             {
421                 hb_error( "Failed to write frame to output file, Disk Full?" );
422                 *job->die = 1;
423             }
424             mk_addFrameData(m->file, mux_data->track, op->packet, op->bytes);
425             mk_setFrameFlags(m->file, mux_data->track, timecode, 1, 0);
426             hb_buffer_close( &buf );
427             return 0;
428         }
429     }
430
431     if( mk_startFrame(m->file, mux_data->track) < 0)
432     {
433         hb_error( "Failed to write frame to output file, Disk Full?" );
434         *job->die = 1;
435     }
436     mk_addFrameData(m->file, mux_data->track, buf->data, buf->size);
437     mk_setFrameFlags(m->file, mux_data->track, timecode,
438                      ((job->vcodec == HB_VCODEC_X264 && 
439                        mux_data == job->mux_data) ? 
440                             (buf->frametype == HB_FRAME_IDR) : 
441                             ((buf->frametype & HB_FRAME_KEY) != 0)), 0 );
442     hb_buffer_close( &buf );
443     return 0;
444 }
445
446 static int MKVEnd( hb_mux_object_t * m )
447 {
448     hb_job_t  *job = m->job;
449     hb_mux_data_t *mux_data = job->mux_data;
450     hb_title_t  *title = job->title;
451     hb_chapter_t *chapter_data;
452     char tmp_buffer[1024];
453     char *string = tmp_buffer;
454
455     if( !job->mux_data )
456     {
457         /*
458          * We must have failed to create the file in the first place.
459          */
460         return 0;
461     }
462
463     chapter_data = hb_list_item( title->list_chapter, mux_data->current_chapter++ );
464
465     if(job->chapter_markers)
466     {
467         tmp_buffer[0] = '\0';
468
469         if( chapter_data != NULL )
470         {
471             string = chapter_data->title;
472         }
473
474         if( strlen(string) == 0 || strlen(string) >= 1024 )
475         {
476             snprintf( tmp_buffer, 1023, "Chapter %02i", mux_data->current_chapter );
477             string = tmp_buffer;
478         }
479         mk_createChapterSimple(m->file, mux_data->prev_chapter_tc, mux_data->prev_chapter_tc, string);
480     }
481
482     if( title->metadata )
483     {
484         hb_metadata_t *md = title->metadata;
485
486         hb_deep_log( 2, "Writing Metadata to output file...");
487         mk_createTagSimple( m->file, MK_TAG_TITLE, md->name );
488         mk_createTagSimple( m->file, "ARTIST", md->artist );
489         mk_createTagSimple( m->file, "COMPOSER", md->composer );
490         mk_createTagSimple( m->file, MK_TAG_SYNOPSIS, md->comment );
491         mk_createTagSimple( m->file, "DATE_RELEASED", md->release_date );
492         // mk_createTagSimple( m->file, "", md->album );
493         mk_createTagSimple( m->file, MK_TAG_GENRE, md->genre );
494     }
495
496     if( mk_close(m->file) < 0 )
497     {
498         hb_error( "Failed to flush the last frame and close the output file, Disk Full?" );
499         *job->die = 1;
500     }
501
502     // TODO: Free what we alloc'd
503
504     return 0;
505 }
506
507 hb_mux_object_t * hb_mux_mkv_init( hb_job_t * job )
508 {
509     hb_mux_object_t * m = calloc( sizeof( hb_mux_object_t ), 1 );
510     m->init      = MKVInit;
511     m->mux       = MKVMux;
512     m->end       = MKVEnd;
513     m->job       = job;
514     return m;
515 }