encode.pl 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use POSIX;
  6. use IPC::Open3;
  7. use File::Basename;
  8. # Default configuration
  9. my $FORMAT = 'mp4';
  10. my $AUDIO_BITRATE = 192;
  11. my $QUALITY = 20;
  12. my $HD_QUALITY = 22;
  13. my $AUDIO_COPY = 0;
  14. my $STEREO_ONLY = 0;
  15. my $VIDEO_ONLY = 0;
  16. my $HEIGHT = undef();
  17. my $WIDTH = undef();
  18. my $AUDIO_EXCLUDE_REGEX = '\b(?:Chinese|Czech|Deutsch|Espanol|Francais|Italiano|Japanese|Korean|Magyar|Polish|Portugues|Thai|Turkish)\b';
  19. my $SUB_INCLUDE_REGEX = '\b(?:English|Unknown|Closed\s+Captions)\b';
  20. my $FORCE_MP4 = 0;
  21. my $OUT_DIR = undef();
  22. my $MIXDOWN_CODEC = 'AAC';
  23. my $MIXDOWN_CHANNELS = 2.0;
  24. my $AAC_ENCODER = 'ffaac';
  25. # Applicaton configuration
  26. my $HD_WIDTH = 1350;
  27. my $MIN_VIDEO_WIDTH = 100;
  28. my $MAX_CROP_DIFF = .1;
  29. my $MAX_DURA_DIFF = 5;
  30. my $NO_CROP = 0;
  31. my @CODEC_ORDER = ('DTS-HD', 'DTS', 'PCM', 'AC3', $MIXDOWN_CODEC, 'OTHER');
  32. my %LANG_INCLUDE_ISO = ('639-1' => 1);
  33. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  34. my $DEBUG = 0;
  35. # General parameters for HandBrake
  36. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--encopts', 'b-adapt=2:rc-lookahead=50');
  37. my @audio_params = ('--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ffac3');
  38. # Use CoreAudio where available
  39. my ($OS) = POSIX::uname();
  40. if ($OS eq 'Darwin') {
  41. $AAC_ENCODER = 'ca_aac';
  42. }
  43. # Runtime debug mode
  44. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  45. $DEBUG = 1;
  46. }
  47. # Shortcut config
  48. if ($ENV{'MOBILE'}) {
  49. $ENV{'QUALITY'} = 24;
  50. $ENV{'HEIGHT'} = 720;
  51. $ENV{'WIDTH'} = 1280;
  52. $ENV{'AUDIO_BITRATE'} = 128;
  53. $ENV{'STEREO_ONLY'} = 1;
  54. }
  55. # Allow overrides for audio languages
  56. if ($ENV{'AUDIO_EXCLUDE_REGEX'}) {
  57. $AUDIO_EXCLUDE_REGEX = $ENV{'AUDIO_EXCLUDE_REGEX'};
  58. }
  59. # Allow overrides for subtitle languages
  60. if ($ENV{'SUB_INCLUDE_REGEX'}) {
  61. $SUB_INCLUDE_REGEX = $ENV{'SUB_INCLUDE_REGEX'};
  62. }
  63. # Allow copy-only audio transfers (for use in re-encoding)
  64. if ($ENV{'AUDIO_COPY'}) {
  65. $AUDIO_COPY = 1;
  66. }
  67. # Allow AAC-only audio transfers (for use in mobile encoding)
  68. if ($ENV{'STEREO_ONLY'}) {
  69. $STEREO_ONLY = 1;
  70. }
  71. # Allow video-only transfers
  72. if ($ENV{'VIDEO_ONLY'}) {
  73. $VIDEO_ONLY = 1;
  74. }
  75. # Allow MP4-only output format (for use in mobile encoding)
  76. if ($ENV{'FORCE_MP4'}) {
  77. $FORCE_MP4 = 1;
  78. }
  79. # Allow overrides for video quality
  80. if ($ENV{'QUALITY'}) {
  81. $QUALITY = $ENV{'QUALITY'};
  82. $HD_QUALITY = $ENV{'QUALITY'};
  83. }
  84. # Allow overrides for audio bitrate
  85. if ($ENV{'AUDIO_BITRATE'}) {
  86. $AUDIO_BITRATE = $ENV{'AUDIO_BITRATE'};
  87. }
  88. # Use an alternate output directory, if specified
  89. if ($ENV{'OUT_DIR'}) {
  90. $OUT_DIR = $ENV{'OUT_DIR'};
  91. $OUT_DIR =~ s/\/+$//;
  92. }
  93. # Allow overrides for video height and width. The default is "same as source".
  94. if ($ENV{'HEIGHT'}) {
  95. push(@video_params, '--maxHeight', $ENV{'HEIGHT'});
  96. }
  97. if ($ENV{'WIDTH'}) {
  98. push(@video_params, '--maxWidth', $ENV{'WIDTH'});
  99. }
  100. # Disable cropping
  101. if ($ENV{'NO_CROP'}) {
  102. $NO_CROP = 1;
  103. }
  104. # Enable greyscale mode
  105. if ($ENV{'GREYSCALE'}) {
  106. push(@video_params, '--grayscale');
  107. }
  108. # Additional arguments for HandBrake, to allow options not supported directly by this script
  109. # Split on spaces; if you need spaces you'll have to work out something else
  110. if ($ENV{'HANDBRAKE_ARGS'}) {
  111. my @args = split(/\s+/, $ENV{'HANDBRAKE_ARGS'});
  112. push(@video_params, @args);
  113. }
  114. # Command-line parameters
  115. my ($in_file, $out_file, $title) = @ARGV;
  116. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  117. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  118. }
  119. # Sanity checks
  120. if ($AUDIO_COPY && $STEREO_ONLY) {
  121. die(basename($0) . ": AUDIO_COPY and STEREO_ONLY are mutually exclusive\n");
  122. }
  123. if ($VIDEO_ONLY && ($AUDIO_COPY || $STEREO_ONLY)) {
  124. die(basename($0) . ": VIDEO_ONLY and AUDIO_COPY or STEREO_ONLY are mutually exclusive\n");
  125. }
  126. # Scan for title/track info
  127. my %titles = &scan($in_file);
  128. # Allow external subtitles for single-title files
  129. if (scalar(keys(%titles)) == 1) {
  130. my $srt_file = $in_file;
  131. $srt_file =~ s/\.\w{2,4}$/.srt/;
  132. if (!-r $srt_file) {
  133. $srt_file =~ s/\.\w{2,4}$/.ssa/;
  134. }
  135. if (-r $srt_file) {
  136. if ($DEBUG) {
  137. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  138. }
  139. push(@video_params, '--srt-file', $srt_file);
  140. }
  141. }
  142. # Allow encoding of a specific title
  143. if ($title) {
  144. if ($title =~ /^\d+$/ && $title > 0) {
  145. if (!defined($titles{$title})) {
  146. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  147. }
  148. my $selected_title = $titles{$title};
  149. %titles = ();
  150. $titles{$title} = $selected_title;
  151. } elsif ($title =~ /main/i) {
  152. my $max_title = 0;
  153. my $max_duration = 0;
  154. foreach my $title (keys(%titles)) {
  155. if (!$titles{$title}{'duration'}) {
  156. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  157. next;
  158. }
  159. my $new_max = 0;
  160. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  161. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  162. $new_max = 1;
  163. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  164. $new_max = 1;
  165. }
  166. } elsif ($titles{$title}{'duration'} > $max_duration) {
  167. $new_max = 1;
  168. }
  169. if ($new_max) {
  170. $max_duration = $titles{$title}{'duration'};
  171. $max_title = $title;
  172. }
  173. }
  174. my $selected_title = $titles{$max_title};
  175. %titles = ();
  176. $titles{$max_title} = $selected_title;
  177. }
  178. }
  179. # Ensure we have an output file name
  180. # Force MKV output if the output file name is provided and ends in .MKV
  181. if (!defined($out_file) || length($out_file) < 1) {
  182. $out_file = $in_file;
  183. } else {
  184. my ($force_format) = $out_file =~ /\.(\w{2,4})$/;
  185. if (defined($force_format) && lc($force_format) eq 'mkv') {
  186. $FORMAT = 'mkv';
  187. }
  188. }
  189. # Override the output directory, if requested
  190. if ($OUT_DIR) {
  191. $out_file = $OUT_DIR . '/' . basename($out_file);
  192. }
  193. # Keep copies of our defaults so we can reset between tracks
  194. my $format_default = $FORMAT;
  195. # Encode each title
  196. foreach my $title (keys(%titles)) {
  197. if ($DEBUG) {
  198. print STDERR 'Setting options for title: ' . $title . "\n";
  199. }
  200. # Reset
  201. $FORMAT = $format_default;
  202. # Select a title
  203. my $scan = $titles{$title};
  204. # Skip tracks that have no video
  205. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  206. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  207. next;
  208. }
  209. # Parse subtitle tracks
  210. my @subs = &subOptions($scan);
  211. # Parse audio tracks, unless we're in VIDEO_ONLY mode
  212. my @audio = ();
  213. if (!$VIDEO_ONLY) {
  214. @audio = &audioOptions($scan);
  215. # Skip tracks that have no audio
  216. if (scalar(@{ $scan->{'audio'} }) < 1 || scalar(@audio) < 1) {
  217. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  218. next;
  219. }
  220. # Set the bitrate for transcoded audio tracks
  221. push(@audio, '--ab', $AUDIO_BITRATE);
  222. }
  223. # Set the video quality, using $HD_QUALITY for images larger than $HD_WIDTH (to allow lower quality on HD streams)
  224. my $title_quality = $QUALITY;
  225. if ($scan->{'size'}[0] > $HD_WIDTH) {
  226. $title_quality = $HD_QUALITY;
  227. }
  228. # Detect unlikely autocrop values
  229. my $bad_crop = 0;
  230. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  231. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  232. {
  233. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  234. $bad_crop = 1;
  235. }
  236. # Disable cropping (if no crop argument is passed, HB will autocrop, so set 0:0:0:0 explictly)
  237. if ($NO_CROP || $bad_crop) {
  238. my @crop = (0, 0, 0, 0);
  239. $scan->{'crop'} = \@crop;
  240. }
  241. # Force MKV muxing if the output contains PGS subtitles (there's no support in the MP4 muxer)
  242. foreach my $track (values(%{ $scan->{'subtitle_selected'} })) {
  243. if ($track->{'type'} eq 'PGS') {
  244. $FORMAT = 'mkv';
  245. last;
  246. }
  247. }
  248. # Force MKV muxing if the output contains DTS audio (technically MP4 supports it but QuickTime hates it)
  249. foreach my $track (values(%{ $scan->{'audio_selected'} })) {
  250. if ($track->{'codec'} =~ /DTS/i) {
  251. $FORMAT = 'mkv';
  252. last;
  253. }
  254. }
  255. # Select a file name extension that matches the format
  256. my $title_out_file = $out_file;
  257. $title_out_file =~ s/\.(?:\w{2,4}|dvdmedia)$//i;
  258. if ($FORMAT eq 'mkv') {
  259. $title_out_file .= '.mkv';
  260. } else {
  261. $title_out_file .= '.m4v';
  262. }
  263. # Force the title number into the output file name if there are multiple titles to be encoded
  264. if (scalar(keys(%titles)) > 1) {
  265. my $title_text = sprintf('%02d', $title);
  266. $title_out_file =~ s/(\.\w{2,4})$/\-${title_text}${1}/;
  267. }
  268. # Output file
  269. if (uc($title_out_file) eq uc($in_file)) {
  270. $title_out_file =~ s/(\.\w{2,4})$/-recode${1}/;
  271. }
  272. # Build the arugment list
  273. my @args = ($HB_EXEC);
  274. push(@args, '--title', $title);
  275. push(@args, '--input', $in_file);
  276. push(@args, '--output', $title_out_file);
  277. push(@args, '--format', $FORMAT);
  278. push(@args, '--quality', $title_quality);
  279. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  280. push(@args, @video_params);
  281. push(@args, @subs);
  282. # Include audio unless specifically excluded
  283. if (!$VIDEO_ONLY) {
  284. push(@args, @audio_params);
  285. push(@args, @audio);
  286. }
  287. if ($DEBUG) {
  288. print STDERR "\n" . join(' ', @args) . "\n\n";
  289. }
  290. # Sanity check
  291. if (-e $title_out_file) {
  292. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  293. next;
  294. }
  295. # Run it
  296. my $child_out = '';
  297. my $child_in = '';
  298. my $pid = open3($child_in, $child_out, $child_out, @args);
  299. close($child_in);
  300. while (<$child_out>) {
  301. if ($DEBUG) {
  302. print STDERR $_;
  303. }
  304. }
  305. waitpid($pid, 0);
  306. close($child_out);
  307. # Provide the new file name if requested
  308. if ($ENV{'RECODE_OUTFILE'}) {
  309. print $title_out_file;
  310. }
  311. }
  312. # Cleanup
  313. exit(0);
  314. sub subOptions($) {
  315. my ($scan) = @_;
  316. my %tracks = ();
  317. foreach my $track (@{ $scan->{'subtitle'} }) {
  318. my ($language, $note, $iso, $text, $type) = $track->{'description'} =~ /^([^\(]+)(?:\s+\(([^\)]+)\))?\s+\(iso(\d+\-\d+)\:\s+\w\w\w\)\s+\((Text|Bitmap)\)\((CC|VOBSUB|PGS|SSA|TX3G|UTF\-\d+)\)/i;
  319. if (!defined($iso)) {
  320. print STDERR 'Could not parse subtitle description: ' . $track->{'description'} . "\n";
  321. next;
  322. }
  323. # Map text/bitmap into a boolean
  324. if ($text =~ /TEXT/i) {
  325. $text = 1;
  326. } else {
  327. $text = 0;
  328. }
  329. # Standardize the codes
  330. $iso = uc($iso);
  331. $type = uc($type);
  332. # Push all parsed data into an array
  333. my %data = ('language' => $language, 'note' => $note, 'iso' => $iso, 'text' => $text, 'type' => $type);
  334. $tracks{ $track->{'index'} } = \%data;
  335. # Print what we found
  336. if ($DEBUG) {
  337. print STDERR 'Found subtitle track: ';
  338. printHash(\%data);
  339. }
  340. }
  341. # Push the parsed data back up the chain
  342. $scan->{'subtitle_parsed'} = \%tracks;
  343. # Select the subtitle tracks we want to keep
  344. my @keep = ();
  345. foreach my $index (keys(%tracks)) {
  346. # Skip PGS tracks when we're forcing MP4 output (they're not allowed by the muxer)
  347. if ($FORCE_MP4 && $tracks{$index}->{'type'} eq 'PGS') {
  348. next;
  349. }
  350. # Keep tracks in our prefered language, and all text-based subtitles (they're small)
  351. if (isValidSubLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  352. push(@keep, $index);
  353. } elsif ($tracks{$index}->{'text'}) {
  354. push(@keep, $index);
  355. } else {
  356. if ($DEBUG) {
  357. print STDERR 'Skipping subtitle ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  358. }
  359. }
  360. }
  361. # Push the selected tracks back up the chain
  362. my %tmp = ();
  363. foreach my $num (@keep) {
  364. $tmp{$num} = $tracks{$num};
  365. }
  366. $scan->{'subtitle_selected'} = \%tmp;
  367. # Send back the argument string (if any)
  368. if (scalar(@keep) < 1) {
  369. return '';
  370. }
  371. return ('--subtitle', join(',', @keep));
  372. }
  373. sub audioOptions($) {
  374. my ($scan) = @_;
  375. my @retval = ();
  376. # Type the audio tracks
  377. my %tracks = ();
  378. foreach my $track (@{ $scan->{'audio'} }) {
  379. my ($language, $codec, $note, $channels, $iso, $specs) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+(?:\(([^\)]*Commentary[^\)]*)\)\s+)?\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(iso(\d+\-\d+)\:\s+\w\w\w\))?(?:,\s+(.*))?/;
  380. if (!defined($channels)) {
  381. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  382. next;
  383. }
  384. # Decode the channels string to a number
  385. if ($channels =~ /(\d+\.\d+)\s+ch/i) {
  386. $channels = $1;
  387. } elsif ($channels =~ /Dolby\s+Surround/i) {
  388. $channels = 3.1;
  389. }
  390. # Standardize the codec
  391. foreach my $code (@CODEC_ORDER) {
  392. my $metacode = quotemeta($code);
  393. if ($codec =~ /${metacode}/i) {
  394. $codec = $code;
  395. last;
  396. } elsif ($code eq 'OTHER') {
  397. if ($codec =~ /MP3/i || $codec =~ /MPEG/i || $codec =~ /MP2/i) {
  398. $codec = $code;
  399. } elsif ($codec eq 'dca') {
  400. print STDERR 'Found incompatible audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  401. $codec = undef();
  402. } else {
  403. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  404. $codec = $code;
  405. }
  406. }
  407. }
  408. # Standardize the specs
  409. my $bitrate = 0;
  410. my $samplerate = 0;
  411. if (!$specs) {
  412. $specs = '';
  413. }
  414. if ($specs =~ /(\d+)bps/) {
  415. $bitrate = $1 / 1000;
  416. } elsif ($specs =~ /(\d+)\s*kb\/s/) {
  417. $bitrate = $1;
  418. }
  419. if ($specs =~ /(\d+)Hz/) {
  420. $samplerate = $1;
  421. }
  422. # Push all parsed data into the array
  423. my %data = (
  424. 'language' => $language,
  425. 'codec' => $codec,
  426. 'channels' => $channels,
  427. 'iso' => $iso,
  428. 'note' => $note,
  429. 'bitrate' => $bitrate,
  430. 'samplerate' => $samplerate,
  431. );
  432. $tracks{ $track->{'index'} } = \%data;
  433. # Print what we found
  434. if ($DEBUG) {
  435. print STDERR 'Found audio track: ';
  436. printHash(\%data);
  437. }
  438. }
  439. # Push the parsed data back up the chain
  440. $scan->{'audio_parsed'} = \%tracks;
  441. # Find the track with the most channels for each codec, and the highest number of channels among all types of tracks
  442. # Then choose the most desired codec among the set of codecs that contain the highest number of channels
  443. # This chooses the track with the most channels for the mixdown, and resolves ties using CODEC_ORDER
  444. my $mixdown = undef();
  445. my %bestByCodec = ();
  446. my $bestCodec = undef();
  447. my $mostChannels = 0;
  448. # Loop point, in case we need to run the selector more than once
  449. SELECT_AUDIO:
  450. foreach my $codec (@CODEC_ORDER) {
  451. $bestByCodec{$codec} = findBestAudioTrack(\%tracks, $codec);
  452. if (defined($bestByCodec{$codec}) && (!defined($bestCodec) || $mostChannels < $tracks{ $bestByCodec{$codec} }->{'channels'})) {
  453. $bestCodec = $codec;
  454. $mostChannels = $tracks{ $bestByCodec{$codec} }->{'channels'};
  455. }
  456. }
  457. foreach my $codec (@CODEC_ORDER) {
  458. if (defined($bestByCodec{$codec}) && $tracks{ $bestByCodec{$codec} }->{'channels'} == $mostChannels) {
  459. $mixdown = $bestByCodec{$codec};
  460. last;
  461. }
  462. }
  463. # Sanity check
  464. if (!defined($mixdown) || $mixdown < 1) {
  465. # If we applied an exclude filter, remove it and try again
  466. if ($AUDIO_EXCLUDE_REGEX ne 'ACCEPT_ALL') {
  467. $AUDIO_EXCLUDE_REGEX = 'ACCEPT_ALL';
  468. print STDERR "No usable audio tracks found in title. Removing exclude filter...\n";
  469. goto SELECT_AUDIO;
  470. }
  471. # If we got no audio, give up -- this file is not valid
  472. print STDERR basename($0) . ": No usable audio tracks in title\n";
  473. return;
  474. }
  475. # Clear the mixdown selection if we're copying audio
  476. if ($AUDIO_COPY) {
  477. $mixdown = undef();
  478. }
  479. # Mixdown track first
  480. my @audio_tracks = ();
  481. if (defined($mixdown) && $mixdown > 0) {
  482. if ($DEBUG) {
  483. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  484. if ($tracks{$mixdown}->{'channels'} > 2) {
  485. push(@retval, '--mixdown', 'dpl2');
  486. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  487. }
  488. }
  489. my %track = ('index' => $mixdown, 'encoder' => $AAC_ENCODER);
  490. push(@audio_tracks, \%track);
  491. }
  492. # Keep all other audio tracks, unless STEREO_ONLY is set
  493. if (!$STEREO_ONLY) {
  494. # Passthru DTS-MA, DTS, AC3, and AAC
  495. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  496. foreach my $index (keys(%tracks)) {
  497. if (defined($mixdown) && $mixdown == $index && $tracks{$index}->{'channels'} <= $MIXDOWN_CHANNELS) {
  498. if ($DEBUG) {
  499. print STDERR 'Skipping passthru of track ' . $index . ' since it is already used as the mixdown track and contains only ' . $tracks{$index}->{'channels'} . " channels\n";
  500. }
  501. next;
  502. } elsif (!$tracks{$index}->{'codec'}) {
  503. if ($DEBUG) {
  504. print STDERR 'Skipping track ' . $index . " due to invalid codec\n";
  505. }
  506. next;
  507. } elsif (!isValidAudioLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  508. if ($DEBUG) {
  509. print STDERR 'Skipping track ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  510. }
  511. next;
  512. } elsif ($FORCE_MP4 && $tracks{$index}->{'codec'} =~ /DTS/i) {
  513. if ($DEBUG) {
  514. print STDERR 'Skipping track ' . $index . " due to DTS codec and FORCE_MP4 flag\n";
  515. }
  516. next;
  517. } else {
  518. my %track = ('index' => $index, 'encoder' => 'copy');
  519. push(@audio_tracks, \%track);
  520. }
  521. }
  522. }
  523. # Push the selected tracks back up the chain
  524. my %sel = ();
  525. foreach my $track (@audio_tracks) {
  526. # Copy the data, rather than just point to it -- we sometimes need modifications
  527. my $index = $track->{'index'};
  528. my %tmp = %{ $tracks{$index} };
  529. # The mixdown track needs special handling -- it appears twice, and with different settings
  530. if ($track->{'encoder'} ne 'copy' && defined($mixdown) && $mixdown > 0 && $track->{'index'} == $mixdown) {
  531. $index .= '_mixdown';
  532. $tmp{'codec'} = $MIXDOWN_CODEC;
  533. $tmp{'channels'} = $MIXDOWN_CHANNELS;
  534. }
  535. # Collect our (possibly modified) hash
  536. $sel{$index} = \%tmp;
  537. }
  538. $scan->{'audio_selected'} = \%sel;
  539. # Consolidate from the hashes
  540. my @output_tracks = ();
  541. my @output_encoders = ();
  542. foreach my $track (@audio_tracks) {
  543. push(@output_tracks, $track->{'index'});
  544. push(@output_encoders, $track->{'encoder'});
  545. }
  546. # Send back the argument strings
  547. push(@retval, '--audio', join(',', @output_tracks));
  548. push(@retval, '--aencoder', join(',', @output_encoders));
  549. return (@retval);
  550. }
  551. sub scan($) {
  552. my ($in_file) = @_;
  553. # Fork to scan the file
  554. my $child_out = '';
  555. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--previews', '30', '--title', '0', '--input', $in_file);
  556. # Loop through the output
  557. my $scan;
  558. my %titles = ();
  559. my $inTitle = 0;
  560. my $zone = '';
  561. while (<$child_out>) {
  562. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  563. if ($DEBUG) {
  564. print STDERR 'Found ' . $1 . " titles in source\n";
  565. }
  566. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  567. my $stream = $1;
  568. my $desc = $2;
  569. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  570. # Save the current title (if any)
  571. if ($inTitle) {
  572. $titles{$inTitle} = $scan;
  573. }
  574. # Grab the new title number
  575. $inTitle = $1;
  576. # Init the data collectors
  577. my @audio = ();
  578. my @crop = ();
  579. my @subtitle = ();
  580. my @size = ();
  581. my %tmp = (
  582. 'audio' => \@audio,
  583. 'crop' => \@crop,
  584. 'subtitle' => \@subtitle,
  585. 'size' => \@size,
  586. 'duration' => 0,
  587. 'aspect' => 0
  588. );
  589. $scan = \%tmp;
  590. if ($DEBUG) {
  591. print STDERR 'Found data for title ' . $1 . "\n";
  592. }
  593. } elsif ($inTitle) {
  594. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  595. push(@{ $scan->{'size'} }, $1, $2);
  596. if ($DEBUG) {
  597. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  598. }
  599. if (/\s+display aspect\: (\d*\.\d+)/) {
  600. $scan->{'aspect'} = $1;
  601. if ($DEBUG) {
  602. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  603. }
  604. }
  605. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  606. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  607. if ($DEBUG) {
  608. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  609. }
  610. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  611. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  612. if ($DEBUG) {
  613. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  614. }
  615. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  616. $zone = 'audio';
  617. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  618. my %track = ('index' => $1, 'description' => $2);
  619. push(@{ $scan->{'audio'} }, \%track);
  620. if ($DEBUG) {
  621. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  622. }
  623. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  624. $zone = 'subtitle';
  625. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  626. my %track = ('index' => $1, 'description' => $2);
  627. push(@{ $scan->{'subtitle'} }, \%track);
  628. if ($DEBUG) {
  629. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  630. }
  631. }
  632. }
  633. }
  634. # Save the last title (if any)
  635. if ($inTitle) {
  636. $titles{$inTitle} = $scan;
  637. }
  638. # Cleanup the scan process
  639. waitpid($pid, 0);
  640. close($child_out);
  641. # Sanity check
  642. if (scalar(keys(%titles)) < 1) {
  643. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  644. }
  645. # Return
  646. return %titles;
  647. }
  648. sub findBestAudioTrack($$) {
  649. my ($tracks, $codec) = @_;
  650. my $best = undef();
  651. my @available = ();
  652. # Find available tracks
  653. for my $index (keys(%{$tracks})) {
  654. my $track = $tracks->{$index};
  655. # Skip tracks not in the specified codec
  656. if (!$track->{'codec'} || $track->{'codec'} ne $codec) {
  657. next;
  658. }
  659. # Skip foreign language tracks
  660. if (!isValidAudioLanguage($track->{'language'}, $track->{'iso'})) {
  661. next;
  662. }
  663. push(@available, $index);
  664. }
  665. if (scalar(@available) < 1) {
  666. return $best;
  667. }
  668. # Find the tracks with the most channels
  669. {
  670. my @most = ();
  671. my $channels = 0;
  672. foreach my $index (@available) {
  673. my $track = $tracks->{$index};
  674. if ($track->{'channels'} > $channels) {
  675. @most = ($index);
  676. $channels = $track->{'channels'};
  677. } elsif ($track->{'channels'} == $channels) {
  678. push(@most, $index);
  679. }
  680. }
  681. @available = @most;
  682. }
  683. if (scalar(@available) < 1) {
  684. return $best;
  685. }
  686. # Find the tracks with the highest bitrate
  687. {
  688. my @highest = ();
  689. my $bitrate = 0;
  690. foreach my $index (@available) {
  691. my $track = $tracks->{$index};
  692. if ($track->{'bitrate'} > $bitrate) {
  693. @highest = ($index);
  694. $bitrate = $track->{'bitrate'};
  695. } elsif ($track->{'bitrate'} == $bitrate) {
  696. push(@highest, $index);
  697. }
  698. }
  699. @available = @highest;
  700. }
  701. if (scalar(@available) < 1) {
  702. return $best;
  703. }
  704. # Find the track if the lowest index
  705. foreach my $index (@available) {
  706. if (!defined($best) || $index < $best) {
  707. $best = $index;
  708. }
  709. }
  710. return $best;
  711. }
  712. sub isValidSubLanguage($) {
  713. my ($lang, $iso) = @_;
  714. if (scalar(keys(%LANG_INCLUDE_ISO)) && defined($iso) && exists($LANG_INCLUDE_ISO{$iso}) && $LANG_INCLUDE_ISO{$iso}) {
  715. return 1;
  716. } elsif ($SUB_INCLUDE_REGEX && $lang =~ /${SUB_INCLUDE_REGEX}/i) {
  717. return 1;
  718. }
  719. return 0;
  720. }
  721. sub isValidAudioLanguage($) {
  722. my ($lang, $iso) = @_;
  723. if (scalar(keys(%LANG_INCLUDE_ISO)) && defined($iso) && $LANG_INCLUDE_ISO{$iso}) {
  724. return 1;
  725. } elsif ($AUDIO_EXCLUDE_REGEX && $lang =~ /${AUDIO_EXCLUDE_REGEX}/i) {
  726. return 0;
  727. }
  728. return 1;
  729. }
  730. sub printHash($) {
  731. my ($data) = @_;
  732. my $first = 1;
  733. foreach my $key (keys(%{$data})) {
  734. if (defined($data->{$key})) {
  735. if ($first) {
  736. $first = 0;
  737. } else {
  738. print STDERR ', ';
  739. }
  740. print STDERR $key . ' => ' . $data->{$key};
  741. }
  742. }
  743. print STDERR "\n";
  744. }