encode.pl 24 KB

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