encode.pl 25 KB

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