encode.pl 23 KB

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