encode.pl 27 KB

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